From 2b6eca9a76c4e6055fa76976dbee8f5dac30e228 Mon Sep 17 00:00:00 2001 From: David Pine Date: Thu, 31 Aug 2023 13:50:37 -0500 Subject: [PATCH 1/3] Address all IDE0032. Use auto-implemented property. --- .../Messaging/AdoNetGatewayListProvider.cs | 9 ++-- .../Shared/Storage/RelationalStorage.cs | 16 ++----- .../IEventDataGenerator.cs | 5 +-- .../EventHub/EventHubAdapterFactory.cs | 20 ++++----- .../ConsulGatewayListProvider.cs | 8 +--- .../ZooKeeperGatewayListProvider.cs | 5 +-- .../Model/MetadataModel.cs | 18 ++++---- .../Model/MethodDescription.cs | 8 ++-- .../SerializerGenerator.cs | 39 ++++++++-------- .../SyntaxGeneration/FSharpUtils.cs | 30 ++++++------- .../GrainCancellationTokenSource.cs | 17 +++---- .../IDs/SystemTargetGrainId.cs | 21 +++++---- .../Messaging/PrefixingBufferWriter.cs | 10 ++--- .../Messaging/StaticGatewayListProvider.cs | 8 +--- .../Runtime/OutgoingCallInvoker.cs | 13 +++--- .../Catalog/StatelessWorkerGrainContext.cs | 11 +++-- .../Core/GrainMethodInvoker.cs | 28 ++++++------ .../MembershipService/ClusterHealthMonitor.cs | 17 ++++--- .../Placement/DeploymentLoadPublisher.cs | 11 +++-- .../CopierTester.cs | 11 +++-- .../FieldCodecTester.cs | 45 +++++++++---------- .../Adaptors/BufferSliceReaderInput.cs | 23 +++++----- .../Buffers/Adaptors/MemoryBufferWriter.cs | 19 ++++---- .../Buffers/Adaptors/SpanBufferWriter.cs | 11 +++-- src/Orleans.Serialization/Serializer.cs | 33 +++++++------- .../Serializers/CodecProvider.cs | 21 +++++---- .../Session/ReferencedObjectCollection.cs | 13 +++--- .../Common/PooledCache/CachedMessageBlock.cs | 25 +++++------ .../QueueBalancer/BestFitBalancer.cs | 10 ++--- src/Orleans.TestingHost/TestCluster.cs | 21 +++++---- .../UnixSocketConnectionListener.cs | 5 +-- .../Utils/AsyncResultHandle.cs | 11 ++--- .../ITransactionalStateFactory.cs | 5 +-- .../State/StorageBatch.cs | 19 ++++---- .../Utilities/ClassSingleSegmentBuffer.cs | 19 ++++---- .../Utilities/SingleSegmentBuffer.cs | 19 ++++---- .../CodeGenTests/IRuntimeCodeGenGrain.cs | 10 +---- .../Utilities/AsyncPipeline.cs | 7 ++- .../InvokableTestInterfaces.cs | 10 +---- .../StreamingTests/StreamTestHelperClasses.cs | 10 ++--- 40 files changed, 274 insertions(+), 367 deletions(-) diff --git a/src/AdoNet/Orleans.Clustering.AdoNet/Messaging/AdoNetGatewayListProvider.cs b/src/AdoNet/Orleans.Clustering.AdoNet/Messaging/AdoNetGatewayListProvider.cs index bedd5d24cd..c2c8affa01 100644 --- a/src/AdoNet/Orleans.Clustering.AdoNet/Messaging/AdoNetGatewayListProvider.cs +++ b/src/AdoNet/Orleans.Clustering.AdoNet/Messaging/AdoNetGatewayListProvider.cs @@ -17,7 +17,7 @@ public class AdoNetGatewayListProvider : IGatewayListProvider private readonly AdoNetClusteringClientOptions options; private RelationalOrleansQueries orleansQueries; private readonly IServiceProvider serviceProvider; - private readonly TimeSpan maxStaleness; + public AdoNetGatewayListProvider( ILogger logger, IServiceProvider serviceProvider, @@ -29,13 +29,10 @@ public AdoNetGatewayListProvider( this.serviceProvider = serviceProvider; this.options = options.Value; this.clusterId = clusterOptions.Value.ClusterId; - this.maxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; + this.MaxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; } - public TimeSpan MaxStaleness - { - get { return this.maxStaleness; } - } + public TimeSpan MaxStaleness { get; } public bool IsUpdatable { diff --git a/src/AdoNet/Shared/Storage/RelationalStorage.cs b/src/AdoNet/Shared/Storage/RelationalStorage.cs index 0a9ccdb4a1..cac5d193d4 100644 --- a/src/AdoNet/Shared/Storage/RelationalStorage.cs +++ b/src/AdoNet/Shared/Storage/RelationalStorage.cs @@ -25,10 +25,6 @@ namespace Orleans.Tests.SqlUtils [DebuggerDisplay("InvariantName = {InvariantName}, ConnectionString = {ConnectionString}")] internal class RelationalStorage: IRelationalStorage { - /// - /// The connection string to use. - /// - private readonly string connectionString; /// /// The invariant name of the connector for this database. @@ -68,13 +64,7 @@ public string InvariantName /// /// The connection string used to connect to the database. /// - public string ConnectionString - { - get - { - return connectionString; - } - } + public string ConnectionString { get; } /// @@ -204,7 +194,7 @@ public static IRelationalStorage CreateInstance(string invariantName, string con /// The connection string this database should use for database operations. private RelationalStorage(string invariantName, string connectionString) { - this.connectionString = connectionString; + this.ConnectionString = connectionString; this.invariantName = invariantName; supportsCommandCancellation = DbConstantsStore.SupportsCommandCancellation(InvariantName); isSynchronousAdoNetImplementation = DbConstantsStore.IsSynchronousAdoNetImplementation(InvariantName); @@ -260,7 +250,7 @@ private async Task, int>> ExecuteAsync( CommandBehavior commandBehavior, CancellationToken cancellationToken) { - using (var connection = DbConnectionFactory.CreateConnection(invariantName, connectionString)) + using (var connection = DbConnectionFactory.CreateConnection(invariantName, ConnectionString)) { await connection.OpenAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); using(var command = connection.CreateCommand()) diff --git a/src/Azure/Orleans.Streaming.EventHubs/Providers/EventDataGeneratorStreamProvider/IEventDataGenerator.cs b/src/Azure/Orleans.Streaming.EventHubs/Providers/EventDataGeneratorStreamProvider/IEventDataGenerator.cs index 54fc927ee1..0e21c6b04b 100644 --- a/src/Azure/Orleans.Streaming.EventHubs/Providers/EventDataGeneratorStreamProvider/IEventDataGenerator.cs +++ b/src/Azure/Orleans.Streaming.EventHubs/Providers/EventDataGeneratorStreamProvider/IEventDataGenerator.cs @@ -72,11 +72,10 @@ public interface IIntCounter internal class IntCounter : IIntCounter { - private int counter = 0; - public int Value { get { return this.counter; } } + public int Value { get; private set; } = 0; public void Increment() { - counter++; + Value++; } } } diff --git a/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubAdapterFactory.cs b/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubAdapterFactory.cs index d56ee87c70..05fbacdc6f 100644 --- a/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubAdapterFactory.cs +++ b/src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubAdapterFactory.cs @@ -46,9 +46,7 @@ public class EventHubAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueu private readonly EventHubReceiverOptions receiverOptions; private readonly StreamStatisticOptions statisticOptions; private readonly StreamCacheEvictionOptions cacheEvictionOptions; - private HashRingBasedPartitionedStreamQueueMapper streamQueueMapper; private string[] partitionIds; - private ConcurrentDictionary receivers; private EventHubProducerClient client; /// @@ -99,8 +97,8 @@ public class EventHubAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueu /// Factory to create a IEventHubReceiver /// protected Func EventHubReceiverFactory; - internal ConcurrentDictionary EventHubReceivers => receivers; - internal HashRingBasedPartitionedStreamQueueMapper EventHubQueueMapper => streamQueueMapper; + internal ConcurrentDictionary EventHubReceivers { get; private set; } + internal HashRingBasedPartitionedStreamQueueMapper EventHubQueueMapper { get; private set; } public EventHubAdapterFactory( string name, @@ -128,7 +126,7 @@ public EventHubAdapterFactory( public virtual void Init() { - this.receivers = new ConcurrentDictionary(); + this.EventHubReceivers = new ConcurrentDictionary(); InitEventHubClient(); @@ -167,10 +165,10 @@ private void InitCheckpointerFactory() /// public async Task CreateAdapter() { - if (this.streamQueueMapper == null) + if (this.EventHubQueueMapper == null) { this.partitionIds = await GetPartitionIdsAsync(); - this.streamQueueMapper = this.QueueMapperFactory(this.partitionIds); + this.EventHubQueueMapper = this.QueueMapperFactory(this.partitionIds); } return this; } @@ -191,7 +189,7 @@ public IQueueAdapterCache GetQueueAdapterCache() public IStreamQueueMapper GetStreamQueueMapper() { //TODO: CreateAdapter must be called first. Figure out how to safely enforce this - return this.streamQueueMapper; + return this.EventHubQueueMapper; } /// @@ -201,7 +199,7 @@ public IStreamQueueMapper GetStreamQueueMapper() /// public Task GetDeliveryFailureHandler(QueueId queueId) { - return this.StreamFailureHandlerFactory(this.streamQueueMapper.QueueToPartition(queueId)); + return this.StreamFailureHandlerFactory(this.EventHubQueueMapper.QueueToPartition(queueId)); } /// @@ -242,7 +240,7 @@ public IQueueCache CreateQueueCache(QueueId queueId) private EventHubAdapterReceiver GetOrCreateReceiver(QueueId queueId) { - return this.receivers.GetOrAdd(queueId, (q, instance) => instance.MakeReceiver(q), this); + return this.EventHubReceivers.GetOrAdd(queueId, (q, instance) => instance.MakeReceiver(q), this); } protected virtual void InitEventHubClient() @@ -270,7 +268,7 @@ private EventHubAdapterReceiver MakeReceiver(QueueId queueId) var config = new EventHubPartitionSettings { Hub = ehOptions, - Partition = this.streamQueueMapper.QueueToPartition(queueId), + Partition = this.EventHubQueueMapper.QueueToPartition(queueId), ReceiverOptions = this.receiverOptions }; diff --git a/src/Orleans.Clustering.Consul/ConsulGatewayListProvider.cs b/src/Orleans.Clustering.Consul/ConsulGatewayListProvider.cs index 17b1a39d5c..897ba33018 100644 --- a/src/Orleans.Clustering.Consul/ConsulGatewayListProvider.cs +++ b/src/Orleans.Clustering.Consul/ConsulGatewayListProvider.cs @@ -17,7 +17,6 @@ public class ConsulGatewayListProvider : IGatewayListProvider private readonly string clusterId; private readonly ILogger logger; private readonly ConsulClusteringOptions options; - private readonly TimeSpan maxStaleness; private readonly string kvRootFolder; public ConsulGatewayListProvider( @@ -28,15 +27,12 @@ public ConsulGatewayListProvider( { this.logger = logger; this.clusterId = clusterOptions.Value.ClusterId; - this.maxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; + this.MaxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; this.options = options.Value; this.kvRootFolder = options.Value.KvRootFolder; } - public TimeSpan MaxStaleness - { - get { return this.maxStaleness; } - } + public TimeSpan MaxStaleness { get; } public bool IsUpdatable { diff --git a/src/Orleans.Clustering.ZooKeeper/ZooKeeperGatewayListProvider.cs b/src/Orleans.Clustering.ZooKeeper/ZooKeeperGatewayListProvider.cs index b5e17a69ea..080773fa69 100644 --- a/src/Orleans.Clustering.ZooKeeper/ZooKeeperGatewayListProvider.cs +++ b/src/Orleans.Clustering.ZooKeeper/ZooKeeperGatewayListProvider.cs @@ -23,7 +23,6 @@ public class ZooKeeperGatewayListProvider : IGatewayListProvider /// The deployment connection string. for eg. "192.168.1.1,192.168.1.2/ClusterId" /// private readonly string _deploymentConnectionString; - private readonly TimeSpan _maxStaleness; public ZooKeeperGatewayListProvider( ILogger logger, @@ -34,7 +33,7 @@ public ZooKeeperGatewayListProvider( _watcher = new ZooKeeperWatcher(logger); _deploymentPath = "/" + clusterOptions.Value.ClusterId; _deploymentConnectionString = options.Value.ConnectionString + _deploymentPath; - _maxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; + MaxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; } /// @@ -61,7 +60,7 @@ public async Task> GetGateways() /// /// Specifies how often this IGatewayListProvider is refreshed, to have a bound on max staleness of its returned information. /// - public TimeSpan MaxStaleness => _maxStaleness; + public TimeSpan MaxStaleness { get; } /// /// Specifies whether this IGatewayListProvider ever refreshes its returned information, or always returns the same gw list. diff --git a/src/Orleans.CodeGenerator/Model/MetadataModel.cs b/src/Orleans.CodeGenerator/Model/MetadataModel.cs index 0a2ad01450..bb80a0b39e 100644 --- a/src/Orleans.CodeGenerator/Model/MetadataModel.cs +++ b/src/Orleans.CodeGenerator/Model/MetadataModel.cs @@ -29,7 +29,6 @@ internal class MetadataModel /// internal sealed class CompoundTypeAliasTree { - private Dictionary _children; /// /// Initializes a new instance of the class. @@ -55,7 +54,7 @@ private CompoundTypeAliasTree(CompoundTypeAliasComponent key, TypeSyntax value) /// public static CompoundTypeAliasTree Create() => new(default, default); - public Dictionary Children => _children; + public Dictionary Children { get; private set; } internal CompoundTypeAliasTree GetChildOrDefault(object key) { @@ -65,7 +64,7 @@ internal CompoundTypeAliasTree GetChildOrDefault(object key) internal bool TryGetChild(object key, out CompoundTypeAliasTree result) { - if (_children is { } children) + if (Children is { } children) { return children.TryGetValue(key, out result); } @@ -127,9 +126,9 @@ public void Add(ReadOnlySpan keys, TypeSyntax value) private CompoundTypeAliasTree AddInternal(CompoundTypeAliasComponent key) => AddInternal(key, default); private CompoundTypeAliasTree AddInternal(CompoundTypeAliasComponent key, TypeSyntax value) { - _children ??= new(); + Children ??= new(); - if (_children.TryGetValue(key, out var existing)) + if (Children.TryGetValue(key, out var existing)) { if (value is not null && existing.Value is not null) { @@ -141,7 +140,7 @@ private CompoundTypeAliasTree AddInternal(CompoundTypeAliasComponent key, TypeSy } else { - return _children[key] = new CompoundTypeAliasTree(key, value); + return Children[key] = new CompoundTypeAliasTree(key, value); } } } @@ -184,21 +183,20 @@ private CompoundTypeAliasTree AddInternal(CompoundTypeAliasComponent key, TypeSy internal readonly struct Either where T : class where U : class { - private readonly bool _isLeft; private readonly object _value; public Either(T value) { _value = value; - _isLeft = true; + IsLeft = true; } public Either(U value) { _value = value; - _isLeft = false; + IsLeft = false; } - public bool IsLeft => _isLeft; + public bool IsLeft { get; } public bool IsRight => !IsLeft; public T LeftValue => (T)_value; public U RightValue => (U)_value; diff --git a/src/Orleans.CodeGenerator/Model/MethodDescription.cs b/src/Orleans.CodeGenerator/Model/MethodDescription.cs index 19f6468d7b..cf9048bfd0 100644 --- a/src/Orleans.CodeGenerator/Model/MethodDescription.cs +++ b/src/Orleans.CodeGenerator/Model/MethodDescription.cs @@ -8,11 +8,9 @@ namespace Orleans.CodeGenerator { internal class MethodDescription { - private readonly InvokableInterfaceDescription _iface; - public MethodDescription(InvokableInterfaceDescription containingType, IMethodSymbol method, string methodId, bool hasCollision) { - _iface = containingType; + ContainingInterface = containingType; Method = method; MethodId = methodId; HasCollision = hasCollision; @@ -21,7 +19,7 @@ public MethodDescription(InvokableInterfaceDescription containingType, IMethodSy AllTypeParameters = new List<(string Name, ITypeParameterSymbol Parameter)>(); MethodTypeParameters = new List<(string Name, ITypeParameterSymbol Parameter)>(); - foreach (var tp in _iface.InterfaceType.GetAllTypeParameters()) + foreach (var tp in ContainingInterface.InterfaceType.GetAllTypeParameters()) { var tpName = GetTypeParameterName(names, tp); AllTypeParameters.Add((tpName, tp)); @@ -149,7 +147,7 @@ bool TryGetNamedArgument(ImmutableArray> arg public IMethodSymbol Method { get; } - public InvokableInterfaceDescription ContainingInterface => _iface; + public InvokableInterfaceDescription ContainingInterface { get; } public bool HasCollision { get; } diff --git a/src/Orleans.CodeGenerator/SerializerGenerator.cs b/src/Orleans.CodeGenerator/SerializerGenerator.cs index c0097cc60c..b0e203718a 100644 --- a/src/Orleans.CodeGenerator/SerializerGenerator.cs +++ b/src/Orleans.CodeGenerator/SerializerGenerator.cs @@ -1123,35 +1123,33 @@ internal interface ISerializableMember /// internal class SerializableMethodMember : ISerializableMember { - private readonly MethodParameterFieldDescription _member; - public SerializableMethodMember(MethodParameterFieldDescription member) { - _member = member; + Member = member; } - IMemberDescription ISerializableMember.Member => _member; - public MethodParameterFieldDescription Member => _member; + IMemberDescription ISerializableMember.Member => Member; + public MethodParameterFieldDescription Member { get; } - private LibraryTypes LibraryTypes => _member.Method.ContainingInterface.CodeGenerator.LibraryTypes; + private LibraryTypes LibraryTypes => Member.Method.ContainingInterface.CodeGenerator.LibraryTypes; - public bool IsShallowCopyable => LibraryTypes.IsShallowCopyable(_member.Parameter.Type) || _member.Parameter.HasAnyAttribute(LibraryTypes.ImmutableAttributes); + public bool IsShallowCopyable => LibraryTypes.IsShallowCopyable(Member.Parameter.Type) || Member.Parameter.HasAnyAttribute(LibraryTypes.ImmutableAttributes); /// /// Gets syntax representing the type of this field. /// - public TypeSyntax TypeSyntax => _member.TypeSyntax; + public TypeSyntax TypeSyntax => Member.TypeSyntax; - public bool IsValueType => _member.Type.IsValueType; + public bool IsValueType => Member.Type.IsValueType; - public bool IsPrimaryConstructorParameter => _member.IsPrimaryConstructorParameter; + public bool IsPrimaryConstructorParameter => Member.IsPrimaryConstructorParameter; /// /// Returns syntax for retrieving the value of this field, deep copying it if necessary. /// /// The instance of the containing type. /// Syntax for retrieving the value of this field. - public ExpressionSyntax GetGetter(ExpressionSyntax instance) => instance.Member(_member.FieldName); + public ExpressionSyntax GetGetter(ExpressionSyntax instance) => instance.Member(Member.FieldName); /// /// Returns syntax for setting the value of this field. @@ -1161,7 +1159,7 @@ public SerializableMethodMember(MethodParameterFieldDescription member) /// Syntax for setting the value of this field. public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) => AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - instance.Member(_member.FieldName), + instance.Member(Member.FieldName), value); public FieldAccessorDescription GetGetterFieldDescription() => null; @@ -1176,7 +1174,6 @@ internal class SerializableMember : ISerializableMember private readonly SemanticModel _model; private readonly LibraryTypes _libraryTypes; private IPropertySymbol _property; - private readonly IMemberDescription _member; /// /// The ordinal assigned to this field. @@ -1188,23 +1185,23 @@ public SerializableMember(LibraryTypes libraryTypes, ISerializableTypeDescriptio _libraryTypes = libraryTypes; _model = type.SemanticModel; _ordinal = ordinal; - _member = member; + Member = member; } - public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(_member.Type) || (Property is { } prop && prop.HasAnyAttribute(_libraryTypes.ImmutableAttributes)) || _member.Symbol.HasAnyAttribute(_libraryTypes.ImmutableAttributes); + public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(Member.Type) || (Property is { } prop && prop.HasAnyAttribute(_libraryTypes.ImmutableAttributes)) || Member.Symbol.HasAnyAttribute(_libraryTypes.ImmutableAttributes); public bool IsValueType => Type.IsValueType; - public IMemberDescription Member => _member; + public IMemberDescription Member { get; } /// /// Gets the underlying instance. /// - private IFieldSymbol Field => (_member as IFieldDescription)?.Field; + private IFieldSymbol Field => (Member as IFieldDescription)?.Field; - public ITypeSymbol Type => _member.Type; + public ITypeSymbol Type => Member.Type; - public INamedTypeSymbol ContainingType => _member.ContainingType; + public INamedTypeSymbol ContainingType => Member.ContainingType; public string MemberName => Field?.Name ?? Property?.Name; @@ -1248,7 +1245,7 @@ public SerializableMember(LibraryTypes libraryTypes, ISerializableTypeDescriptio /// public TypeSyntax TypeSyntax => Member.Type.TypeKind == TypeKind.Dynamic ? PredefinedType(Token(SyntaxKind.ObjectKeyword)) - : _member.GetTypeSyntax(Member.Type); + : Member.GetTypeSyntax(Member.Type); /// /// Gets the which this field is the backing property for, or @@ -1262,7 +1259,7 @@ public SerializableMember(LibraryTypes libraryTypes, ISerializableTypeDescriptio private bool IsObsolete => Member.Symbol.HasAttribute(_libraryTypes.ObsoleteAttribute) || Property != null && Property.HasAttribute(_libraryTypes.ObsoleteAttribute); - public bool IsPrimaryConstructorParameter => _member.IsPrimaryConstructorParameter; + public bool IsPrimaryConstructorParameter => Member.IsPrimaryConstructorParameter; /// /// Returns syntax for retrieving the value of this field, deep copying it if necessary. diff --git a/src/Orleans.CodeGenerator/SyntaxGeneration/FSharpUtils.cs b/src/Orleans.CodeGenerator/SyntaxGeneration/FSharpUtils.cs index 63416dfc08..89b19cb9c5 100644 --- a/src/Orleans.CodeGenerator/SyntaxGeneration/FSharpUtils.cs +++ b/src/Orleans.CodeGenerator/SyntaxGeneration/FSharpUtils.cs @@ -150,30 +150,29 @@ public int Compare(IPropertySymbol x, IPropertySymbol y) private class FSharpUnionCaseFieldDescription : IMemberDescription, ISerializableMember { private readonly LibraryTypes _libraryTypes; - private readonly IPropertySymbol _property; public FSharpUnionCaseFieldDescription(LibraryTypes libraryTypes, IPropertySymbol property, uint ordinal) { _libraryTypes = libraryTypes; FieldId = ordinal; - _property = property; + Property = property; } public uint FieldId { get; } - public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(Type) || _property.HasAnyAttribute(_libraryTypes.ImmutableAttributes); + public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(Type) || Property.HasAnyAttribute(_libraryTypes.ImmutableAttributes); public bool IsValueType => Type.IsValueType; public IMemberDescription Member => this; - public ITypeSymbol Type => _property.Type; + public ITypeSymbol Type => Property.Type; - public INamedTypeSymbol ContainingType => _property.ContainingType; + public INamedTypeSymbol ContainingType => Property.ContainingType; - public ISymbol Symbol => _property; + public ISymbol Symbol => Property; - public string FieldName => _property.Name.ToLowerInvariant(); + public string FieldName => Property.Name.ToLowerInvariant(); /// /// Gets the name of the setter field. @@ -191,7 +190,7 @@ public FSharpUnionCaseFieldDescription(LibraryTypes libraryTypes, IPropertySymbo /// Gets the which this field is the backing property for, or /// if this is not the backing field of an auto-property. /// - private IPropertySymbol Property => _property; + private IPropertySymbol Property { get; } public string AssemblyName => Type.ContainingAssembly.ToDisplayName(); public string TypeName => Type.ToDisplayName(); @@ -263,30 +262,29 @@ private static IEnumerable GetRecordDataMembers(LibraryTypes private class FSharpRecordPropertyDescription : IMemberDescription, ISerializableMember { private readonly LibraryTypes _libraryTypes; - private readonly IPropertySymbol _property; public FSharpRecordPropertyDescription(LibraryTypes libraryTypes, IPropertySymbol property, uint ordinal) { _libraryTypes = libraryTypes; FieldId = ordinal; - _property = property; + Property = property; } public uint FieldId { get; } - public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(Type) || _property.HasAnyAttribute(_libraryTypes.ImmutableAttributes); + public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(Type) || Property.HasAnyAttribute(_libraryTypes.ImmutableAttributes); public bool IsValueType => Type.IsValueType; public IMemberDescription Member => this; - public ITypeSymbol Type => _property.Type; + public ITypeSymbol Type => Property.Type; - public ISymbol Symbol => _property; + public ISymbol Symbol => Property; - public INamedTypeSymbol ContainingType => _property.ContainingType; + public INamedTypeSymbol ContainingType => Property.ContainingType; - public string FieldName => _property.Name + "@"; + public string FieldName => Property.Name + "@"; /// /// Gets the name of the setter field. @@ -304,7 +302,7 @@ public FSharpRecordPropertyDescription(LibraryTypes libraryTypes, IPropertySymbo /// Gets the which this field is the backing property for, or /// if this is not the backing field of an auto-property. /// - private IPropertySymbol Property => _property; + private IPropertySymbol Property { get; } public string AssemblyName => Type.ContainingAssembly.ToDisplayName(); public string TypeName => Type.ToDisplayName(); diff --git a/src/Orleans.Core.Abstractions/Cancellation/GrainCancellationTokenSource.cs b/src/Orleans.Core.Abstractions/Cancellation/GrainCancellationTokenSource.cs index 21517f65a2..422385b5f7 100644 --- a/src/Orleans.Core.Abstractions/Cancellation/GrainCancellationTokenSource.cs +++ b/src/Orleans.Core.Abstractions/Cancellation/GrainCancellationTokenSource.cs @@ -9,17 +9,13 @@ namespace Orleans /// public sealed class GrainCancellationTokenSource : IDisposable { - /// - /// The underlying grain cancellation token. - /// - private readonly GrainCancellationToken _grainCancellationToken; /// /// Initializes the . /// public GrainCancellationTokenSource() { - _grainCancellationToken = new GrainCancellationToken(Guid.NewGuid()); + Token = new GrainCancellationToken(Guid.NewGuid()); } /// @@ -28,10 +24,7 @@ public GrainCancellationTokenSource() /// /// The CancellationToken /// associated with this . - public GrainCancellationToken Token - { - get { return _grainCancellationToken; } - } + public GrainCancellationToken Token { get; } /// /// Gets a value indicating whether cancellation has been requested. @@ -48,7 +41,7 @@ public GrainCancellationToken Token /// public bool IsCancellationRequested { - get { return _grainCancellationToken.IsCancellationRequested; } + get { return Token.IsCancellationRequested; } } /// @@ -70,7 +63,7 @@ public bool IsCancellationRequested /// This has been disposed. public Task Cancel() { - return _grainCancellationToken.Cancel(); + return Token.Cancel(); } /// @@ -81,7 +74,7 @@ public Task Cancel() /// public void Dispose() { - _grainCancellationToken.Dispose(); + Token.Dispose(); } } } \ No newline at end of file diff --git a/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs b/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs index ced25fbeae..3de070c52d 100644 --- a/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs +++ b/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs @@ -14,7 +14,6 @@ namespace Orleans.Runtime public readonly struct SystemTargetGrainId : IEquatable, IComparable, ISpanFormattable { private const char SegmentSeparator = '+'; - private readonly GrainId _grainId; /// /// Initializes a new instance of the struct. @@ -22,12 +21,12 @@ namespace Orleans.Runtime /// /// The grain id. /// - private SystemTargetGrainId(GrainId grainId) => _grainId = grainId; + private SystemTargetGrainId(GrainId grainId) => GrainId = grainId; /// /// Gets the underlying identity. /// - public GrainId GrainId => _grainId; + public GrainId GrainId { get; } /// /// Creates a new instance. @@ -121,7 +120,7 @@ public static bool TryParse(GrainId grainId, out SystemTargetGrainId systemTarge public SystemTargetGrainId WithSiloAddress(SiloAddress siloAddress) { var addr = siloAddress.ToUtf8String(); - var key = _grainId.Key.AsSpan(); + var key = GrainId.Key.AsSpan(); if (key.IndexOf((byte)SegmentSeparator) is int index && index >= 0) { var extraIdentifier = key.Slice(index + 1); @@ -133,7 +132,7 @@ public SystemTargetGrainId WithSiloAddress(SiloAddress siloAddress) addr = buf; } - return new SystemTargetGrainId(new GrainId(_grainId.Type, new IdSpan(addr))); + return new SystemTargetGrainId(new GrainId(GrainId.Type, new IdSpan(addr))); } /// @@ -144,7 +143,7 @@ public SystemTargetGrainId WithSiloAddress(SiloAddress siloAddress) /// public SiloAddress GetSiloAddress() { - var key = _grainId.Key.AsSpan(); + var key = GrainId.Key.AsSpan(); if (key.IndexOf((byte)SegmentSeparator) is int index && index >= 0) { key = key.Slice(0, index); @@ -215,24 +214,24 @@ internal static GrainId CreateGrainServiceGrainId(GrainType grainType, SiloAddre public static GrainType CreateGrainType(string name) => GrainType.Create($"{GrainTypePrefix.SystemTargetPrefix}{name}"); /// - public bool Equals(SystemTargetGrainId other) => _grainId.Equals(other._grainId); + public bool Equals(SystemTargetGrainId other) => GrainId.Equals(other.GrainId); /// public override bool Equals(object? obj) => obj is SystemTargetGrainId observer && this.Equals(observer); /// - public override int GetHashCode() => _grainId.GetHashCode(); + public override int GetHashCode() => GrainId.GetHashCode(); /// - public override string ToString() => _grainId.ToString(); + public override string ToString() => GrainId.ToString(); string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => ToString(); bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider) - => ((ISpanFormattable)_grainId).TryFormat(destination, out charsWritten, format, provider); + => ((ISpanFormattable)GrainId).TryFormat(destination, out charsWritten, format, provider); /// - public int CompareTo(SystemTargetGrainId other) => _grainId.CompareTo(other._grainId); + public int CompareTo(SystemTargetGrainId other) => GrainId.CompareTo(other.GrainId); /// /// Compares the provided operands for equality. diff --git a/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs b/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs index 7d0db0b3a6..a74d2b6d52 100644 --- a/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs +++ b/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs @@ -56,8 +56,6 @@ internal sealed class PrefixingBufferWriter : IBufferWriter, IDisposable /// private Sequence privateWriter; - private int _committedBytes; - /// /// Initializes a new instance of the class. /// @@ -77,7 +75,7 @@ public PrefixingBufferWriter(int prefixSize, int payloadSizeHint, MemoryPool throw new ArgumentOutOfRangeException(nameof(prefixSize)); } - public int CommittedBytes => _committedBytes; + public int CommittedBytes { get; private set; } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -86,7 +84,7 @@ public void Advance(int count) if (privateWriter == null) { advanced += count; - _committedBytes += count; + CommittedBytes += count; } else { @@ -98,7 +96,7 @@ public void Advance(int count) private void AdvancePrivateWriter(int count) { privateWriter.Advance(count); - _committedBytes += count; + CommittedBytes += count; } /// @@ -184,7 +182,7 @@ public void Reset() realMemory = default; innerWriter = null; advanced = 0; - _committedBytes = 0; + CommittedBytes = 0; } public void Dispose() diff --git a/src/Orleans.Core/Messaging/StaticGatewayListProvider.cs b/src/Orleans.Core/Messaging/StaticGatewayListProvider.cs index f7b9123a63..63df96027b 100644 --- a/src/Orleans.Core/Messaging/StaticGatewayListProvider.cs +++ b/src/Orleans.Core/Messaging/StaticGatewayListProvider.cs @@ -12,7 +12,6 @@ namespace Orleans.Messaging public class StaticGatewayListProvider : IGatewayListProvider { private readonly StaticGatewayListProviderOptions options; - private readonly TimeSpan maxStaleness; /// /// Initializes a new instance of the class. @@ -22,7 +21,7 @@ public class StaticGatewayListProvider : IGatewayListProvider public StaticGatewayListProvider(IOptions options, IOptions gatewayOptions) { this.options = options.Value; - this.maxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; + this.MaxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod; } /// @@ -32,10 +31,7 @@ public StaticGatewayListProvider(IOptions opti public Task> GetGateways() => Task.FromResult>(this.options.Gateways); /// - public TimeSpan MaxStaleness - { - get => this.maxStaleness; - } + public TimeSpan MaxStaleness { get; } /// public bool IsUpdatable diff --git a/src/Orleans.Core/Runtime/OutgoingCallInvoker.cs b/src/Orleans.Core/Runtime/OutgoingCallInvoker.cs index 8ed01f6e4e..0f9e33a996 100644 --- a/src/Orleans.Core/Runtime/OutgoingCallInvoker.cs +++ b/src/Orleans.Core/Runtime/OutgoingCallInvoker.cs @@ -11,7 +11,6 @@ namespace Orleans.Runtime /// internal sealed class OutgoingCallInvoker : IOutgoingGrainCallContext { - private readonly IInvokable request; private readonly InvokeMethodOptions options; private readonly Action sendRequest; private readonly IOutgoingGrainCallFilter[] filters; @@ -35,7 +34,7 @@ public OutgoingCallInvoker( Action sendRequest, IOutgoingGrainCallFilter[] filters) { - this.request = request; + this.Request = request; this.options = options; this.sendRequest = sendRequest; this.grainReference = grain; @@ -50,11 +49,11 @@ public OutgoingCallInvoker( } } - public IInvokable Request => this.request; + public IInvokable Request { get; } public object Grain => this.grainReference; - public MethodInfo InterfaceMethod => request.GetMethod(); + public MethodInfo InterfaceMethod => Request.GetMethod(); public object Result { get => TypedResult; set => TypedResult = (TResult)value; } @@ -70,9 +69,9 @@ public OutgoingCallInvoker( public GrainInterfaceType InterfaceType => grainReference.InterfaceType; - public string InterfaceName => request.GetInterfaceName(); + public string InterfaceName => Request.GetInterfaceName(); - public string MethodName => request.GetMethodName(); + public string MethodName => Request.GetMethodName(); public async Task Invoke() { @@ -113,7 +112,7 @@ public async Task Invoke() // Finally call the root-level invoker. stage++; var responseCompletionSource = ResponseCompletionSourcePool.Get(); - this.sendRequest(this.grainReference, responseCompletionSource, this.request, this.options); + this.sendRequest(this.grainReference, responseCompletionSource, this.Request, this.options); this.Response = await responseCompletionSource.AsValueTask(); return; diff --git a/src/Orleans.Runtime/Catalog/StatelessWorkerGrainContext.cs b/src/Orleans.Runtime/Catalog/StatelessWorkerGrainContext.cs index a6a7667361..82935c2c20 100644 --- a/src/Orleans.Runtime/Catalog/StatelessWorkerGrainContext.cs +++ b/src/Orleans.Runtime/Catalog/StatelessWorkerGrainContext.cs @@ -10,7 +10,6 @@ namespace Orleans.Runtime { internal class StatelessWorkerGrainContext : IGrainContext, IAsyncDisposable, IActivationLifecycleObserver { - private readonly GrainAddress _address; private readonly GrainTypeSharedContext _shared; private readonly IGrainContextActivator _innerActivator; private readonly int _maxWorkers; @@ -35,7 +34,7 @@ public StatelessWorkerGrainContext( GrainTypeSharedContext sharedContext, IGrainContextActivator innerActivator) { - _address = address; + Address = address; _shared = sharedContext; _innerActivator = innerActivator; _maxWorkers = ((StatelessWorkerPlacement)_shared.PlacementStrategy).MaxLocal; @@ -45,13 +44,13 @@ public StatelessWorkerGrainContext( public GrainReference GrainReference => _grainReference ??= _shared.GrainReferenceActivator.CreateReference(GrainId, default); - public GrainId GrainId => _address.GrainId; + public GrainId GrainId => Address.GrainId; public object GrainInstance => null; - public ActivationId ActivationId => _address.ActivationId; + public ActivationId ActivationId => Address.ActivationId; - public GrainAddress Address => _address; + public GrainAddress Address { get; } public IServiceProvider ActivationServices => throw new NotImplementedException(); @@ -237,7 +236,7 @@ private void ReceiveMessageInternal(object message) private ActivationData CreateWorker(object message) { - var address = GrainAddress.GetAddress(_address.SiloAddress, _address.GrainId, ActivationId.NewId()); + var address = GrainAddress.GetAddress(Address.SiloAddress, Address.GrainId, ActivationId.NewId()); var newWorker = (ActivationData)_innerActivator.CreateContext(address); // Observe the create/destroy lifecycle of the activation diff --git a/src/Orleans.Runtime/Core/GrainMethodInvoker.cs b/src/Orleans.Runtime/Core/GrainMethodInvoker.cs index b4d1229627..61be9d4702 100644 --- a/src/Orleans.Runtime/Core/GrainMethodInvoker.cs +++ b/src/Orleans.Runtime/Core/GrainMethodInvoker.cs @@ -15,11 +15,9 @@ namespace Orleans.Runtime internal sealed class GrainMethodInvoker : IIncomingGrainCallContext { private readonly Message message; - private readonly IInvokable request; private readonly List filters; private readonly InterfaceToImplementationMappingCache interfaceToImplementationMapping; private readonly DeepCopier responseCopier; - private readonly IGrainContext grainContext; private int stage; /// @@ -40,18 +38,18 @@ public GrainMethodInvoker( DeepCopier responseCopier) { this.message = message; - this.request = request; - this.grainContext = grainContext; + this.Request = request; + this.TargetContext = grainContext; this.filters = filters; this.interfaceToImplementationMapping = interfaceToImplementationMapping; this.responseCopier = responseCopier; } - public IInvokable Request => request; + public IInvokable Request { get; } - public object Grain => grainContext.GrainInstance; + public object Grain => TargetContext.GrainInstance; - public MethodInfo InterfaceMethod => request.GetMethod(); + public MethodInfo InterfaceMethod => Request.GetMethod(); public MethodInfo ImplementationMethod => GetMethodEntry().ImplementationMethod; @@ -69,15 +67,15 @@ public object Result public GrainId? SourceId => message.SendingGrain is { IsDefault: false } source ? source : null; - public IGrainContext TargetContext => grainContext; + public IGrainContext TargetContext { get; } - public GrainId TargetId => grainContext.GrainId; + public GrainId TargetId => TargetContext.GrainId; public GrainInterfaceType InterfaceType => message.InterfaceType; - public string InterfaceName => request.GetInterfaceName(); + public string InterfaceName => Request.GetInterfaceName(); - public string MethodName => request.GetMethodName(); + public string MethodName => Request.GetMethodName(); public async Task Invoke() { @@ -124,7 +122,7 @@ public async Task Invoke() { // Finally call the root-level invoker. stage++; - this.Response = await request.Invoke(); + this.Response = await Request.Invoke(); // Propagate exceptions to other filters. if (this.Response.Exception is { } exception) @@ -160,8 +158,8 @@ private static void ThrowBrokenCallFilterChain(string filterName) private (MethodInfo ImplementationMethod, MethodInfo InterfaceMethod) GetMethodEntry() { - var interfaceType = this.request.GetInterfaceType(); - var implementationType = this.request.GetTarget().GetType(); + var interfaceType = this.Request.GetInterfaceType(); + var implementationType = this.Request.GetTarget().GetType(); // Get or create the implementation map for this object. var implementationMap = interfaceToImplementationMapping.GetOrCreate( @@ -169,7 +167,7 @@ private static void ThrowBrokenCallFilterChain(string filterName) interfaceType); // Get the method info for the method being invoked. - var method = request.GetMethod(); + var method = Request.GetMethod(); if (method.IsConstructedGenericMethod) { if (implementationMap.TryGetValue(method.GetGenericMethodDefinition(), out var entry)) diff --git a/src/Orleans.Runtime/MembershipService/ClusterHealthMonitor.cs b/src/Orleans.Runtime/MembershipService/ClusterHealthMonitor.cs index 8909ce9037..1a84604a13 100644 --- a/src/Orleans.Runtime/MembershipService/ClusterHealthMonitor.cs +++ b/src/Orleans.Runtime/MembershipService/ClusterHealthMonitor.cs @@ -26,7 +26,6 @@ internal class ClusterHealthMonitor : IHealthCheckParticipant, ILifecyclePartici private readonly ILogger log; private readonly IFatalErrorHandler fatalErrorHandler; private readonly IOptionsMonitor clusterMembershipOptions; - private ImmutableDictionary monitoredSilos = ImmutableDictionary.Empty; private MembershipVersion observedMembershipVersion; private Func createMonitor; private Func onProbeResult; @@ -61,7 +60,7 @@ public ClusterHealthMonitor( this.createMonitor = silo => ActivatorUtilities.CreateInstance(serviceProvider, silo, onProbeResultFunc); } - ImmutableDictionary ITestAccessor.MonitoredSilos { get => this.monitoredSilos; set => this.monitoredSilos = value; } + ImmutableDictionary ITestAccessor.MonitoredSilos { get => this.SiloMonitors; set => this.SiloMonitors = value; } Func ITestAccessor.CreateMonitor { get => this.createMonitor; set => this.createMonitor = value; } MembershipVersion ITestAccessor.ObservedVersion => this.observedMembershipVersion; Func ITestAccessor.OnProbeResult { get => this.onProbeResult; set => this.onProbeResult = value; } @@ -69,7 +68,7 @@ public ClusterHealthMonitor( /// /// Gets the collection of monitored silos. /// - public ImmutableDictionary SiloMonitors => this.monitoredSilos; + public ImmutableDictionary SiloMonitors { get; private set; } = ImmutableDictionary.Empty; private async Task ProcessMembershipUpdates() { @@ -78,9 +77,9 @@ private async Task ProcessMembershipUpdates() if (this.log.IsEnabled(LogLevel.Debug)) this.log.LogDebug("Starting to process membership updates"); await foreach (var tableSnapshot in this.membershipService.MembershipTableUpdates.WithCancellation(this.shutdownCancellation.Token)) { - var newMonitoredSilos = this.UpdateMonitoredSilos(tableSnapshot, this.monitoredSilos, DateTime.UtcNow); + var newMonitoredSilos = this.UpdateMonitoredSilos(tableSnapshot, this.SiloMonitors, DateTime.UtcNow); - foreach (var pair in this.monitoredSilos) + foreach (var pair in this.SiloMonitors) { if (!newMonitoredSilos.ContainsKey(pair.Key)) { @@ -89,7 +88,7 @@ private async Task ProcessMembershipUpdates() } } - this.monitoredSilos = newMonitoredSilos; + this.SiloMonitors = newMonitoredSilos; this.observedMembershipVersion = tableSnapshot.Version; } } @@ -216,12 +215,12 @@ async Task OnActiveStop(CancellationToken ct) { this.shutdownCancellation.Cancel(throwOnFirstException: false); - foreach (var monitor in this.monitoredSilos.Values) + foreach (var monitor in this.SiloMonitors.Values) { tasks.Add(monitor.StopAsync(ct)); } - this.monitoredSilos = ImmutableDictionary.Empty; + this.SiloMonitors = ImmutableDictionary.Empty; // Allow some minimum time for graceful shutdown. var shutdownGracePeriod = Task.WhenAll(Task.Delay(ClusterMembershipOptions.ClusteringShutdownGracePeriod), ct.WhenCancelled()); @@ -265,7 +264,7 @@ bool IHealthCheckable.CheckHealth(DateTime lastCheckTime, out string reason) { var ok = true; reason = default; - foreach (var monitor in this.monitoredSilos.Values) + foreach (var monitor in this.SiloMonitors.Values) { ok &= monitor.CheckHealth(lastCheckTime, out var monitorReason); if (!string.IsNullOrWhiteSpace(monitorReason)) diff --git a/src/Orleans.Runtime/Placement/DeploymentLoadPublisher.cs b/src/Orleans.Runtime/Placement/DeploymentLoadPublisher.cs index 80a4dab25c..7928b9cfdf 100644 --- a/src/Orleans.Runtime/Placement/DeploymentLoadPublisher.cs +++ b/src/Orleans.Runtime/Placement/DeploymentLoadPublisher.cs @@ -24,7 +24,6 @@ internal class DeploymentLoadPublisher : SystemTarget, IDeploymentLoadPublisher, private readonly IAppEnvironmentStatistics _appEnvironmentStatistics; private readonly IHostEnvironmentStatistics _hostEnvironmentStatistics; private readonly IOptions _loadSheddingOptions; - private readonly ConcurrentDictionary _periodicStats; private readonly TimeSpan _statisticsRefreshTime; private readonly List _siloStatisticsChangeListeners; private readonly ILogger _logger; @@ -32,7 +31,7 @@ internal class DeploymentLoadPublisher : SystemTarget, IDeploymentLoadPublisher, private long _lastUpdateDateTimeTicks; private IDisposable _publishTimer; - public ConcurrentDictionary PeriodicStatistics => _periodicStats; + public ConcurrentDictionary PeriodicStatistics { get; } public SiloRuntimeStatistics LocalRuntimeStatistics { get; private set; } @@ -59,7 +58,7 @@ public DeploymentLoadPublisher( _hostEnvironmentStatistics = hostEnvironmentStatistics; _loadSheddingOptions = loadSheddingOptions; _statisticsRefreshTime = options.Value.DeploymentLoadPublisherRefreshTime; - _periodicStats = new ConcurrentDictionary(); + PeriodicStatistics = new ConcurrentDictionary(); _siloStatisticsChangeListeners = new List(); } @@ -166,12 +165,12 @@ private void UpdateRuntimeStatisticsInternal(SiloAddress siloAddress, SiloRuntim } // Take only if newer. - if (_periodicStats.TryGetValue(siloAddress, out var old) && old.DateTime > siloStats.DateTime) + if (PeriodicStatistics.TryGetValue(siloAddress, out var old) && old.DateTime > siloStats.DateTime) { return; } - _periodicStats[siloAddress] = siloStats; + PeriodicStatistics[siloAddress] = siloStats; NotifyAllStatisticsChangeEventsSubscribers(siloAddress, siloStats); } @@ -262,7 +261,7 @@ private void OnSiloStatusChange(SiloAddress updatedSilo, SiloStatus status) _publishTimer.Dispose(); } - _periodicStats.TryRemove(updatedSilo, out _); + PeriodicStatistics.TryRemove(updatedSilo, out _); NotifyAllStatisticsChangeEventsSubscribers(updatedSilo, null); } } diff --git a/src/Orleans.Serialization.TestKit/CopierTester.cs b/src/Orleans.Serialization.TestKit/CopierTester.cs index aed279cc80..f02302e6a5 100644 --- a/src/Orleans.Serialization.TestKit/CopierTester.cs +++ b/src/Orleans.Serialization.TestKit/CopierTester.cs @@ -13,7 +13,6 @@ namespace Orleans.Serialization.TestKit [ExcludeFromCodeCoverage] public abstract class CopierTester where TCopier : class, IDeepCopier { - private readonly IServiceProvider _serviceProvider; private readonly CodecProvider _codecProvider; protected CopierTester(ITestOutputHelper output) @@ -35,13 +34,13 @@ protected CopierTester(ITestOutputHelper output) _ = services.AddSerializer(Configure); - _serviceProvider = services.BuildServiceProvider(); - _codecProvider = _serviceProvider.GetRequiredService(); + ServiceProvider = services.BuildServiceProvider(); + _codecProvider = ServiceProvider.GetRequiredService(); } protected Random Random { get; } - protected IServiceProvider ServiceProvider => _serviceProvider; + protected IServiceProvider ServiceProvider { get; } protected virtual bool IsImmutable => false; @@ -49,7 +48,7 @@ protected virtual void Configure(ISerializerBuilder builder) { } - protected virtual TCopier CreateCopier() => _serviceProvider.GetRequiredService(); + protected virtual TCopier CreateCopier() => ServiceProvider.GetRequiredService(); protected abstract TValue CreateValue(); protected abstract TValue[] TestValues { get; } protected virtual bool Equals(TValue left, TValue right) => EqualityComparer.Default.Equals(left, right); @@ -90,7 +89,7 @@ public void ReferencesAreAddedToCopyContext() var value = CreateValue(); var array = new TValue[] { value, value }; - var arrayCopier = _serviceProvider.GetRequiredService>(); + var arrayCopier = ServiceProvider.GetRequiredService>(); var arrayCopy = arrayCopier.Copy(array); Assert.Same(arrayCopy[0], arrayCopy[1]); diff --git a/src/Orleans.Serialization.TestKit/FieldCodecTester.cs b/src/Orleans.Serialization.TestKit/FieldCodecTester.cs index 58961bf599..4e70ba9ed0 100644 --- a/src/Orleans.Serialization.TestKit/FieldCodecTester.cs +++ b/src/Orleans.Serialization.TestKit/FieldCodecTester.cs @@ -22,7 +22,6 @@ namespace Orleans.Serialization.TestKit [ExcludeFromCodeCoverage] public abstract class FieldCodecTester : IDisposable where TCodec : class, IFieldCodec { - private readonly IServiceProvider _serviceProvider; private readonly SerializerSessionPool _sessionPool; protected FieldCodecTester(ITestOutputHelper output) @@ -44,13 +43,13 @@ protected FieldCodecTester(ITestOutputHelper output) _ = services.AddSerializer(Configure); - _serviceProvider = services.BuildServiceProvider(); - _sessionPool = _serviceProvider.GetService(); + ServiceProvider = services.BuildServiceProvider(); + _sessionPool = ServiceProvider.GetService(); } protected Random Random { get; } - protected IServiceProvider ServiceProvider => _serviceProvider; + protected IServiceProvider ServiceProvider { get; } protected SerializerSessionPool SessionPool => _sessionPool; @@ -60,14 +59,14 @@ protected virtual void Configure(ISerializerBuilder builder) { } - protected virtual TCodec CreateCodec() => _serviceProvider.GetRequiredService(); + protected virtual TCodec CreateCodec() => ServiceProvider.GetRequiredService(); protected abstract TValue CreateValue(); protected abstract TValue[] TestValues { get; } protected virtual bool Equals(TValue left, TValue right) => EqualityComparer.Default.Equals(left, right); protected virtual Action> ValueProvider { get; } - void IDisposable.Dispose() => (_serviceProvider as IDisposable)?.Dispose(); + void IDisposable.Dispose() => (ServiceProvider as IDisposable)?.Dispose(); [Fact] public void CorrectlyAdvancesReferenceCounterStream() @@ -169,7 +168,7 @@ public void CorrectlyAdvancesReferenceCounter() [Fact] public void CanRoundTripViaSerializer_StreamPooled() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -203,7 +202,7 @@ void Test(TValue original) [Fact] public void CanRoundTripViaSerializer_Span() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -235,7 +234,7 @@ void Test(TValue original) [Fact] public void CanRoundTripViaSerializer_Array() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -267,7 +266,7 @@ void Test(TValue original) [Fact] public void CanRoundTripViaSerializer_Memory() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -299,7 +298,7 @@ void Test(TValue original) [Fact] public void CanRoundTripViaSerializer_MemoryStream() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -338,7 +337,7 @@ void Test(TValue original) [Fact] public void CanRoundTripViaSerializer_ReadByteByByte() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -373,7 +372,7 @@ void Test(TValue original) [Fact] public void ProducesValidBitStream() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var value in TestValues) { Test(value); @@ -405,7 +404,7 @@ void Test(TValue value) [Fact] public void WritersProduceSameResults() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -508,7 +507,7 @@ void Test(TValue original) [Fact] public void CanRoundTripCollectionViaSerializer() { - var serializer = _serviceProvider.GetRequiredService>>(); + var serializer = ServiceProvider.GetRequiredService>>(); var original = new List(); original.AddRange(TestValues); @@ -540,7 +539,7 @@ public void CanRoundTripCollectionViaSerializer() [Fact] public void CanCopyCollectionViaSerializer() { - var copier = _serviceProvider.GetRequiredService>>(); + var copier = ServiceProvider.GetRequiredService>>(); var original = new List(); original.AddRange(TestValues); @@ -564,7 +563,7 @@ public void CanCopyCollectionViaSerializer() [Fact] public void CanCopyCollectionViaUntypedSerializer() { - var copier = _serviceProvider.GetRequiredService>>(); + var copier = ServiceProvider.GetRequiredService>>(); var original = new List(); foreach (var value in TestValues) @@ -592,7 +591,7 @@ public void CanCopyCollectionViaUntypedSerializer() [Fact] public void CanCopyTupleViaSerializer_Untyped() { - var copier = _serviceProvider.GetRequiredService>(); + var copier = ServiceProvider.GetRequiredService>(); var value = TestValues.Reverse().Concat(new[] { CreateValue(), CreateValue() }).Take(2).ToArray(); var original = (Guid.NewGuid().ToString(), (object)value[0], (object)value[1], Guid.NewGuid().ToString()); @@ -620,7 +619,7 @@ public void CanCopyTupleViaSerializer_Untyped() [Fact] public void CanCopyTupleViaSerializer() { - var copier = _serviceProvider.GetRequiredService>(); + var copier = ServiceProvider.GetRequiredService>(); var original = (Guid.NewGuid().ToString(), CreateValue(), CreateValue(), Guid.NewGuid().ToString()); @@ -647,7 +646,7 @@ public void CanCopyTupleViaSerializer() [Fact] public void CanRoundTripTupleViaSerializer() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); var original = (Guid.NewGuid().ToString(), CreateValue(), CreateValue(), Guid.NewGuid().ToString()); @@ -682,7 +681,7 @@ public void CanRoundTripTupleViaSerializer() [Fact] public void CanRoundTripViaSerializer() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); foreach (var original in TestValues) { @@ -716,7 +715,7 @@ void Test(TValue original) [Fact] public void CanRoundTripViaObjectSerializer() { - var serializer = _serviceProvider.GetRequiredService>(); + var serializer = ServiceProvider.GetRequiredService>(); var buffer = new byte[10240]; @@ -771,7 +770,7 @@ public void CanRoundTripViaObjectSerializer() [Fact] public void CorrectlyHandlesBuffers() { - var testers = BufferTestHelper.GetTestSerializers(_serviceProvider, MaxSegmentSizes); + var testers = BufferTestHelper.GetTestSerializers(ServiceProvider, MaxSegmentSizes); foreach (var tester in testers) { diff --git a/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs b/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs index fad13ebba3..6cae24fb70 100644 --- a/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs +++ b/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs @@ -14,7 +14,6 @@ public struct BufferSliceReaderInput private static readonly SequenceSegment FinalSegmentSentinel = new(); private readonly BufferSlice _slice; private SequenceSegment _segment; - private int _position; /// /// Initializes a new instance of the type. @@ -27,7 +26,7 @@ public BufferSliceReaderInput(in BufferSlice slice) } internal readonly PooledBuffer Buffer => _slice._buffer; - internal readonly int Position => _position; + internal int Position { get; private set; } internal readonly int Offset => _slice._offset; internal readonly int Length => _slice._length; internal long PreviousBuffersSize; @@ -52,12 +51,12 @@ internal ReadOnlySpan GetNext() // Find the starting segment and the offset to copy from. int segmentOffset; - if (_position < Offset) + if (Position < Offset) { - if (_position + segment.Length <= Offset) + if (Position + segment.Length <= Offset) { // Start is in a subsequent segment - _position += segment.Length; + Position += segment.Length; _segment = _segment.Next as SequenceSegment; continue; } @@ -72,7 +71,7 @@ internal ReadOnlySpan GetNext() segmentOffset = 0; } - var segmentLength = Math.Min(segment.Length - segmentOffset, endPosition - (_position + segmentOffset)); + var segmentLength = Math.Min(segment.Length - segmentOffset, endPosition - (Position + segmentOffset)); if (segmentLength == 0) { ThrowInsufficientData(); @@ -80,15 +79,15 @@ internal ReadOnlySpan GetNext() } var result = segment.Slice(segmentOffset, segmentLength); - _position += segmentOffset + segmentLength; + Position += segmentOffset + segmentLength; _segment = _segment.Next as SequenceSegment; return result; } - if (_segment != FinalSegmentSentinel && Buffer._currentPosition > 0 && Buffer._writeHead is { } head && _position < endPosition) + if (_segment != FinalSegmentSentinel && Buffer._currentPosition > 0 && Buffer._writeHead is { } head && Position < endPosition) { - var finalOffset = Math.Max(Offset - _position, 0); - var finalLength = Math.Min(Buffer._currentPosition, endPosition - (_position + finalOffset)); + var finalOffset = Math.Max(Offset - Position, 0); + var finalLength = Math.Min(Buffer._currentPosition, endPosition - (Position + finalOffset)); if (finalLength == 0) { ThrowInsufficientData(); @@ -96,8 +95,8 @@ internal ReadOnlySpan GetNext() } var result = head.Array.AsSpan(finalOffset, finalLength); - _position += finalOffset + finalLength; - Debug.Assert(_position == endPosition); + Position += finalOffset + finalLength; + Debug.Assert(Position == endPosition); _segment = FinalSegmentSentinel; return result; } diff --git a/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs b/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs index 9cd7e780e2..17af2490c3 100644 --- a/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs +++ b/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs @@ -9,7 +9,6 @@ namespace Orleans.Serialization.Buffers.Adaptors public struct MemoryBufferWriter : IBufferWriter { private readonly Memory _buffer; - private int _bytesWritten; /// /// Initializes a new instance of the struct. @@ -18,50 +17,50 @@ public struct MemoryBufferWriter : IBufferWriter internal MemoryBufferWriter(Memory buffer) { _buffer = buffer; - _bytesWritten = 0; + BytesWritten = 0; } /// /// Gets the number of bytes written. /// /// The number of bytes written. - public int BytesWritten => _bytesWritten; + public int BytesWritten { get; private set; } /// public void Advance(int count) { - if (_bytesWritten > _buffer.Length) + if (BytesWritten > _buffer.Length) { ThrowInvalidCount(); static void ThrowInvalidCount() => throw new InvalidOperationException("Cannot advance past the end of the buffer"); } - _bytesWritten += count; + BytesWritten += count; } /// public Memory GetMemory(int sizeHint = 0) { - if (_bytesWritten + sizeHint >= _buffer.Length) + if (BytesWritten + sizeHint >= _buffer.Length) { ThrowInsufficientCapacity(sizeHint); } - return _buffer.Slice(_bytesWritten); + return _buffer.Slice(BytesWritten); } /// public Span GetSpan(int sizeHint = 0) { - if (_bytesWritten + sizeHint >= _buffer.Length) + if (BytesWritten + sizeHint >= _buffer.Length) { ThrowInsufficientCapacity(sizeHint); } - return _buffer.Span.Slice(_bytesWritten); + return _buffer.Span.Slice(BytesWritten); } - private void ThrowInsufficientCapacity(int sizeHint) => throw new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_buffer.Length}. Current length is {_bytesWritten} and requested size increase is {sizeHint}"); + private void ThrowInsufficientCapacity(int sizeHint) => throw new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_buffer.Length}. Current length is {BytesWritten} and requested size increase is {sizeHint}"); } } diff --git a/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs b/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs index e93775b0c8..50783f797a 100644 --- a/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs +++ b/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs @@ -9,7 +9,6 @@ namespace Orleans.Serialization.Buffers.Adaptors public struct SpanBufferWriter : IBufferWriter { private readonly int _maxLength; - private int _bytesWritten; /// /// Initializes a new instance of the struct. @@ -18,17 +17,17 @@ public struct SpanBufferWriter : IBufferWriter internal SpanBufferWriter(Span buffer) { _maxLength = buffer.Length; - _bytesWritten = 0; + BytesWritten = 0; } /// /// Gets the number of bytes written. /// /// The number of bytes written. - public int BytesWritten => _bytesWritten; + public int BytesWritten { get; private set; } /// - public void Advance(int count) => _bytesWritten += count; + public void Advance(int count) => BytesWritten += count; /// public Memory GetMemory(int sizeHint = 0) => throw GetException(sizeHint); @@ -38,8 +37,8 @@ internal SpanBufferWriter(Span buffer) private Exception GetException(int sizeHint) { - return _bytesWritten + sizeHint > _maxLength - ? new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_maxLength}. Current length is {_bytesWritten} and requested size increase is {sizeHint}") + return BytesWritten + sizeHint > _maxLength + ? new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_maxLength}. Current length is {BytesWritten} and requested size increase is {sizeHint}") : new NotSupportedException("Method is not supported on this instance"); } } diff --git a/src/Orleans.Serialization/Serializer.cs b/src/Orleans.Serialization/Serializer.cs index 85dcf31585..7820a15bd6 100644 --- a/src/Orleans.Serialization/Serializer.cs +++ b/src/Orleans.Serialization/Serializer.cs @@ -16,34 +16,33 @@ namespace Orleans.Serialization /// public sealed class Serializer { - private readonly SerializerSessionPool _sessionPool; /// /// Initializes a new instance of the class. /// /// The session pool. - public Serializer(SerializerSessionPool sessionPool) => _sessionPool = sessionPool; + public Serializer(SerializerSessionPool sessionPool) => SessionPool = sessionPool; /// /// Gets the serializer session pool. /// - public SerializerSessionPool SessionPool => _sessionPool; + public SerializerSessionPool SessionPool { get; } /// /// Returns a serializer which is specialized to the provided type parameter. /// /// The underlying type for the returned serializer. - public Serializer GetSerializer() => new(_sessionPool); + public Serializer GetSerializer() => new(SessionPool); /// /// Returns if the provided type, , can be serialized, and otherwise. /// - public bool CanSerialize() => _sessionPool.CodecProvider.TryGetCodec(typeof(T)) is { }; + public bool CanSerialize() => SessionPool.CodecProvider.TryGetCodec(typeof(T)) is { }; /// /// Returns if the provided type, , can be serialized, and otherwise. /// - public bool CanSerialize(Type type) => _sessionPool.CodecProvider.TryGetCodec(type) is { }; + public bool CanSerialize(Type type) => SessionPool.CodecProvider.TryGetCodec(type) is { }; /// /// Serializes the provided into a new array. @@ -53,7 +52,7 @@ public sealed class Serializer /// A byte array containing the serialized value. public byte[] SerializeToArray(T value) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var writer = Writer.CreatePooled(session); try { @@ -77,7 +76,7 @@ public byte[] SerializeToArray(T value) /// This method slices the to the serialized data length. public void Serialize(T value, ref Memory destination) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var writer = Writer.Create(destination, session); var codec = session.CodecProvider.GetCodec(); codec.WriteField(ref writer, 0, typeof(T), value); @@ -114,7 +113,7 @@ public void Serialize(T value, Stream destination, int sizeHint = 0) { if (destination is MemoryStream memoryStream) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var writer = Writer.Create(memoryStream, session); var codec = session.CodecProvider.GetCodec(); codec.WriteField(ref writer, 0, typeof(T), value); @@ -122,7 +121,7 @@ public void Serialize(T value, Stream destination, int sizeHint = 0) } else { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var writer = Writer.CreatePooled(destination, session, sizeHint); try { @@ -182,7 +181,7 @@ public void Serialize(T value, Stream destination, SerializerSession session, /// The destination where serialized data will be written. public void Serialize(T value, TBufferWriter destination) where TBufferWriter : IBufferWriter { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var writer = Writer.Create(destination, session); var codec = session.CodecProvider.GetCodec(); codec.WriteField(ref writer, 0, typeof(T), value); @@ -232,7 +231,7 @@ public void Serialize(T value, ref Writer desti /// This method slices the to the serialized data length. public void Serialize(T value, ref Span destination) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var writer = Writer.Create(destination, session); var codec = session.CodecProvider.GetCodec(); codec.WriteField(ref writer, 0, typeof(T), value); @@ -266,7 +265,7 @@ public void Serialize(T value, ref Span destination, SerializerSession /// The length of the serialized data. public int Serialize(T value, byte[] destination) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var writer = Writer.Create(destination, session); var codec = session.CodecProvider.GetCodec(); codec.WriteField(ref writer, 0, typeof(T), value); @@ -328,7 +327,7 @@ public int Serialize(T value, byte[] destination, SerializerSession session) /// The deserialized value. public T Deserialize(Stream source) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var reader = Reader.Create(source, session); var codec = session.CodecProvider.GetCodec(); var field = reader.ReadFieldHeader(); @@ -358,7 +357,7 @@ public T Deserialize(Stream source, SerializerSession session) /// The deserialized value. public T Deserialize(ReadOnlySequence source) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var reader = Reader.Create(source, session); var codec = session.CodecProvider.GetCodec(); var field = reader.ReadFieldHeader(); @@ -388,7 +387,7 @@ public T Deserialize(ReadOnlySequence source, SerializerSession session /// The deserialized value. public T Deserialize(PooledBuffer.BufferSlice source) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var reader = Reader.Create(source, session); var codec = session.CodecProvider.GetCodec(); var field = reader.ReadFieldHeader(); @@ -418,7 +417,7 @@ public T Deserialize(PooledBuffer.BufferSlice source, SerializerSession sessi /// The deserialized value. public T Deserialize(ReadOnlySpan source) { - using var session = _sessionPool.GetSession(); + using var session = SessionPool.GetSession(); var reader = Reader.Create(source, session); var codec = session.CodecProvider.GetCodec(); var field = reader.ReadFieldHeader(); diff --git a/src/Orleans.Serialization/Serializers/CodecProvider.cs b/src/Orleans.Serialization/Serializers/CodecProvider.cs index dc08d04272..f441c03cf9 100644 --- a/src/Orleans.Serialization/Serializers/CodecProvider.cs +++ b/src/Orleans.Serialization/Serializers/CodecProvider.cs @@ -47,7 +47,6 @@ public sealed class CodecProvider : ICodecProvider private readonly ObjectCodec _objectCodec = new(); private readonly VoidCodec _voidCodec = new(); private readonly ObjectCopier _objectCopier = new(); - private readonly IServiceProvider _serviceProvider; private readonly VoidCopier _voidCopier = new(); private bool _initialized; @@ -58,13 +57,13 @@ public sealed class CodecProvider : ICodecProvider /// The codec configuration. public CodecProvider(IServiceProvider serviceProvider, IOptions codecConfiguration) { - _serviceProvider = serviceProvider; + Services = serviceProvider; ConsumeMetadata(codecConfiguration); } /// - public IServiceProvider Services => _serviceProvider; + public IServiceProvider Services { get; } private void Initialize() { @@ -75,13 +74,13 @@ private void Initialize() return; } - _generalizedCodecs.AddRange(_serviceProvider.GetServices()); - _generalizedBaseCodecs.AddRange(_serviceProvider.GetServices()); - _generalizedCopiers.AddRange(_serviceProvider.GetServices()); + _generalizedCodecs.AddRange(Services.GetServices()); + _generalizedBaseCodecs.AddRange(Services.GetServices()); + _generalizedCopiers.AddRange(Services.GetServices()); - _specializableCodecs.AddRange(_serviceProvider.GetServices()); - _specializableCopiers.AddRange(_serviceProvider.GetServices()); - _specializableBaseCodecs.AddRange(_serviceProvider.GetServices()); + _specializableCodecs.AddRange(Services.GetServices()); + _specializableCopiers.AddRange(Services.GetServices()); + _specializableBaseCodecs.AddRange(Services.GetServices()); _initialized = true; } @@ -475,13 +474,13 @@ private object GetServiceOrCreateInstance(Type type, object[] constructorArgumen return result; } - result = _serviceProvider.GetService(type); + result = Services.GetService(type); if (result != null) { return result; } - result = ActivatorUtilities.CreateInstance(_serviceProvider, type, constructorArguments ?? Array.Empty()); + result = ActivatorUtilities.CreateInstance(Services, type, constructorArguments ?? Array.Empty()); return result; } diff --git a/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs b/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs index 7066806f21..c6c4aaaedb 100644 --- a/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs +++ b/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs @@ -41,7 +41,6 @@ public ReferencePair(uint id, object @object) private Dictionary _referenceToObjectOverflow; private Dictionary _objectToReferenceOverflow; - private uint _currentReferenceId; /// /// Tries to get the referenced object with the specified id. @@ -67,9 +66,9 @@ public object TryGetReferencedObject(uint reference) /// Marks a value field. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void MarkValueField() => ++_currentReferenceId; + public void MarkValueField() => ++CurrentReferenceId; - internal uint CreateRecordPlaceholder() => ++_currentReferenceId; + internal uint CreateRecordPlaceholder() => ++CurrentReferenceId; /// /// Gets or adds a reference. @@ -81,7 +80,7 @@ public object TryGetReferencedObject(uint reference) public bool GetOrAddReference(object value, out uint reference) { // Unconditionally bump the reference counter since a call to this method signifies a potential reference. - var nextReference = ++_currentReferenceId; + var nextReference = ++CurrentReferenceId; // Null is always at reference 0 if (value is null) @@ -183,7 +182,7 @@ private void CreateObjectToReferenceOverflow(object value) objects[i] = default; } - result[value] = _currentReferenceId; + result[value] = CurrentReferenceId; _objectToReferenceCount = 0; _objectToReferenceOverflow = result; @@ -262,7 +261,7 @@ void CreateReferenceToObjectOverflow() /// /// The value. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void RecordReferenceField(object value) => RecordReferenceField(value, ++_currentReferenceId); + public void RecordReferenceField(object value) => RecordReferenceField(value, ++CurrentReferenceId); /// /// Records a reference field with the specified identifier. @@ -296,7 +295,7 @@ public void RecordReferenceField(object value, uint referenceId) /// Gets or sets the current reference identifier. /// /// The current reference identifier. - public uint CurrentReferenceId { get => _currentReferenceId; set => _currentReferenceId = value; } + public uint CurrentReferenceId { get; set; } /// /// Resets this instance. diff --git a/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs b/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs index b7522bcf8f..10e3a3d957 100644 --- a/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs +++ b/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs @@ -19,7 +19,6 @@ public class CachedMessageBlock : PooledResource private readonly CachedMessage[] cachedMessages; private readonly int blockSize; private int writeIndex; - private int readIndex; /// /// Linked list node, so this message block can be kept in a linked list. @@ -34,7 +33,7 @@ public class CachedMessageBlock : PooledResource /// /// Gets a value indicating whether this block is empty. /// - public bool IsEmpty => readIndex >= writeIndex; + public bool IsEmpty => OldestMessageIndex >= writeIndex; /// /// Gets the index of most recent message added to the block. @@ -44,7 +43,7 @@ public class CachedMessageBlock : PooledResource /// /// Gets the index of the oldest message in this block. /// - public int OldestMessageIndex => readIndex; + public int OldestMessageIndex { get; private set; } /// /// Gets the oldest message in the block. @@ -61,7 +60,7 @@ public class CachedMessageBlock : PooledResource /// public int ItemCount { get { - int count = writeIndex - readIndex; + int count = writeIndex - OldestMessageIndex; return count >= 0 ? count : 0; } } @@ -75,7 +74,7 @@ public CachedMessageBlock(int blockSize = DefaultCachedMessagesPerBlock) this.blockSize = blockSize; cachedMessages = new CachedMessage[blockSize]; writeIndex = 0; - readIndex = 0; + OldestMessageIndex = 0; Node = new LinkedListNode(this); } @@ -85,9 +84,9 @@ public CachedMessageBlock(int blockSize = DefaultCachedMessagesPerBlock) /// if there are more items remaining; otherwise . public bool Remove() { - if (readIndex < writeIndex) + if (OldestMessageIndex < writeIndex) { - readIndex++; + OldestMessageIndex++; return true; } return false; @@ -120,7 +119,7 @@ public CachedMessage this[int index] { get { - if (index >= writeIndex || index < readIndex) + if (index >= writeIndex || index < OldestMessageIndex) { throw new ArgumentOutOfRangeException(nameof(index)); } @@ -136,7 +135,7 @@ public CachedMessage this[int index] /// The sequence token. public StreamSequenceToken GetSequenceToken(int index, ICacheDataAdapter dataAdapter) { - if (index >= writeIndex || index < readIndex) + if (index >= writeIndex || index < OldestMessageIndex) { throw new ArgumentOutOfRangeException(nameof(index)); } @@ -170,7 +169,7 @@ public StreamSequenceToken GetOldestSequenceToken(ICacheDataAdapter dataAdapter) /// The index of the first message in this block that has a sequence token equal to or before the provided token. public int GetIndexOfFirstMessageLessThanOrEqualTo(StreamSequenceToken token) { - for (int i = writeIndex - 1; i >= readIndex; i--) + for (int i = writeIndex - 1; i >= OldestMessageIndex; i--) { if (cachedMessages[i].Compare(token) <= 0) { @@ -189,7 +188,7 @@ public int GetIndexOfFirstMessageLessThanOrEqualTo(StreamSequenceToken token) /// if the message was found, otherwise. public bool TryFindFirstMessage(StreamId streamId, ICacheDataAdapter dataAdapter, out int index) { - return TryFindNextMessage(readIndex, streamId, dataAdapter, out index); + return TryFindNextMessage(OldestMessageIndex, streamId, dataAdapter, out index); } /// @@ -202,7 +201,7 @@ public bool TryFindFirstMessage(StreamId streamId, ICacheDataAdapter dataAdapter /// if the message was found, otherwise. public bool TryFindNextMessage(int start, StreamId streamId, ICacheDataAdapter dataAdapter, out int index) { - if (start < readIndex) + if (start < OldestMessageIndex) { throw new ArgumentOutOfRangeException(nameof(start)); } @@ -224,7 +223,7 @@ public bool TryFindNextMessage(int start, StreamId streamId, ICacheDataAdapter d public override void OnResetState() { writeIndex = 0; - readIndex = 0; + OldestMessageIndex = 0; } } } diff --git a/src/Orleans.Streaming/QueueBalancer/BestFitBalancer.cs b/src/Orleans.Streaming/QueueBalancer/BestFitBalancer.cs index 8348a0d3f8..c1f408dffb 100644 --- a/src/Orleans.Streaming/QueueBalancer/BestFitBalancer.cs +++ b/src/Orleans.Streaming/QueueBalancer/BestFitBalancer.cs @@ -32,9 +32,7 @@ internal class BestFitBalancer where TBucket : IEquatable, IComparable where TResource : IEquatable, IComparable { - private readonly Dictionary> idealDistribution; - - public Dictionary> IdealDistribution { get { return idealDistribution; } } + public Dictionary> IdealDistribution { get; } /// /// Constructor. @@ -54,7 +52,7 @@ public BestFitBalancer(IEnumerable buckets, IEnumerable reso throw new ArgumentNullException(nameof(resources)); } - idealDistribution = BuildIdealDistribution(buckets, resources); + IdealDistribution = BuildIdealDistribution(buckets, resources); } /// @@ -75,7 +73,7 @@ public Dictionary> GetDistribution(IEnumerable HashSet activeBucketsSet = new HashSet(activeBuckets); foreach (var bucket in activeBucketsSet) { - if (!idealDistribution.ContainsKey(bucket)) + if (!IdealDistribution.ContainsKey(bucket)) { throw new ArgumentOutOfRangeException(nameof(activeBuckets), String.Format("Active buckets contain a bucket {0} not in the master list.", bucket)); } @@ -90,7 +88,7 @@ public Dictionary> GetDistribution(IEnumerable // setup ideal distribution for active buckets and build list of all resources that need redistributed from inactive buckets var resourcesToRedistribute = new List(); - foreach (var kv in idealDistribution) + foreach (var kv in IdealDistribution) { if (activeBucketsSet.Contains(kv.Key)) newDistribution.Add(kv.Key, kv.Value); diff --git a/src/Orleans.TestingHost/TestCluster.cs b/src/Orleans.TestingHost/TestCluster.cs index 84f29ead37..7532f8eae6 100644 --- a/src/Orleans.TestingHost/TestCluster.cs +++ b/src/Orleans.TestingHost/TestCluster.cs @@ -31,7 +31,6 @@ namespace Orleans.TestingHost public class TestCluster : IDisposable, IAsyncDisposable { private readonly List additionalSilos = new List(); - private readonly TestClusterOptions options; private readonly StringBuilder log = new StringBuilder(); private readonly InMemoryTransportConnectionHub _transportHub = new(); private bool _disposed; @@ -85,7 +84,7 @@ public ReadOnlyCollection Silos /// This is the options you configured your test cluster with, or the default one. /// If the cluster is being configured via ClusterConfiguration, then this object may not reflect the true settings. /// - public TestClusterOptions Options => this.options; + public TestClusterOptions Options { get; } /// /// The internal client interface. @@ -135,7 +134,7 @@ public TestCluster( IReadOnlyList configurationSources, ITestClusterPortAllocator portAllocator) { - this.options = options; + this.Options = options; this.ConfigurationSources = configurationSources.ToArray(); this.PortAllocator = portAllocator; this.CreateSiloAsync = DefaultCreateSiloAsync; @@ -165,7 +164,7 @@ public async Task DeployAsync() WriteLog(startMsg); await InitializeAsync(); - if (this.options.InitializeClientOnDeploy) + if (this.Options.InitializeClientOnDeploy) { await WaitForInitialStabilization(); } @@ -342,7 +341,7 @@ public async Task> StartAdditionalSilosAsync(int silosToStart, if (silosToStart > 0) { var siloStartTasks = Enumerable.Range(this.startedInstances, silosToStart) - .Select(instanceNumber => Task.Run(() => StartSiloAsync((short)instanceNumber, this.options, startSiloOnNewPort: startAdditionalSiloOnNewPort))).ToArray(); + .Select(instanceNumber => Task.Run(() => StartSiloAsync((short)instanceNumber, this.Options, startSiloOnNewPort: startAdditionalSiloOnNewPort))).ToArray(); try { @@ -516,7 +515,7 @@ public async Task RestartSiloAsync(SiloHandle instance) var instanceNumber = instance.InstanceNumber; var siloName = instance.Name; await StopSiloAsync(instance); - var newInstance = await StartSiloAsync(instanceNumber, this.options); + var newInstance = await StartSiloAsync(instanceNumber, this.Options); if (siloName == Silo.PrimarySiloName) { @@ -544,7 +543,7 @@ public async Task RestartStoppedSecondarySiloAsync(string siloName) { if (siloName == null) throw new ArgumentNullException(nameof(siloName)); var siloHandle = this.Silos.Single(s => s.Name.Equals(siloName, StringComparison.Ordinal)); - var newInstance = await this.StartSiloAsync(this.Silos.IndexOf(siloHandle), this.options); + var newInstance = await this.StartSiloAsync(this.Silos.IndexOf(siloHandle), this.Options); lock (additionalSilos) { additionalSilos.Add(newInstance); @@ -605,11 +604,11 @@ public async Task InitializeClientAsync() private async Task InitializeAsync() { - short silosToStart = this.options.InitialSilosCount; + short silosToStart = this.Options.InitialSilosCount; - if (this.options.UseTestClusterMembership) + if (this.Options.UseTestClusterMembership) { - this.Primary = await StartSiloAsync(this.startedInstances, this.options); + this.Primary = await StartSiloAsync(this.startedInstances, this.Options); silosToStart--; } @@ -620,7 +619,7 @@ private async Task InitializeAsync() WriteLog("Done initializing cluster"); - if (this.options.InitializeClientOnDeploy) + if (this.Options.InitializeClientOnDeploy) { await InitializeClientAsync(); } diff --git a/src/Orleans.TestingHost/UnixSocketTransport/UnixSocketConnectionListener.cs b/src/Orleans.TestingHost/UnixSocketTransport/UnixSocketConnectionListener.cs index 7cdcbd6262..43dfbbac30 100644 --- a/src/Orleans.TestingHost/UnixSocketTransport/UnixSocketConnectionListener.cs +++ b/src/Orleans.TestingHost/UnixSocketTransport/UnixSocketConnectionListener.cs @@ -12,7 +12,6 @@ namespace Orleans.TestingHost.UnixSocketTransport; internal class UnixSocketConnectionListener : IConnectionListener { private readonly UnixDomainSocketEndPoint _unixEndpoint; - private readonly EndPoint _endpoint; private readonly UnixSocketConnectionOptions _socketConnectionOptions; private readonly SocketsTrace _trace; private readonly SocketSchedulers _schedulers; @@ -22,14 +21,14 @@ internal class UnixSocketConnectionListener : IConnectionListener public UnixSocketConnectionListener(UnixDomainSocketEndPoint unixEndpoint, EndPoint endpoint, UnixSocketConnectionOptions socketConnectionOptions, SocketsTrace trace, SocketSchedulers schedulers) { _unixEndpoint = unixEndpoint; - _endpoint = endpoint; + EndPoint = endpoint; _socketConnectionOptions = socketConnectionOptions; _trace = trace; _schedulers = schedulers; _memoryPool = socketConnectionOptions.MemoryPoolFactory(); } - public EndPoint EndPoint => _endpoint; + public EndPoint EndPoint { get; } public void Bind() { diff --git a/src/Orleans.TestingHost/Utils/AsyncResultHandle.cs b/src/Orleans.TestingHost/Utils/AsyncResultHandle.cs index 38f63c3eae..c1139e0abc 100644 --- a/src/Orleans.TestingHost/Utils/AsyncResultHandle.cs +++ b/src/Orleans.TestingHost/Utils/AsyncResultHandle.cs @@ -8,7 +8,6 @@ namespace Orleans.TestingHost.Utils /// public class AsyncResultHandle { - bool done = false; bool continueFlag = false; /// Reset the current result handle @@ -16,16 +15,12 @@ public virtual void Reset() { Exception = null; Result = null; - done = false; + Done = false; continueFlag = false; } /// Get or set the Done flag - public bool Done - { - get { return done; } - set { done = value; } - } + public bool Done { get; set; } = false; /// Get or set the Continue flag public bool Continue @@ -46,7 +41,7 @@ public bool Continue /// Returns true if operation completes before timeout public Task WaitForFinished(TimeSpan timeout) { - return WaitFor(timeout, () => done); + return WaitFor(timeout, () => Done); } /// diff --git a/src/Orleans.Transactions/Abstractions/ITransactionalStateFactory.cs b/src/Orleans.Transactions/Abstractions/ITransactionalStateFactory.cs index 8e985a21a1..47117f4be9 100644 --- a/src/Orleans.Transactions/Abstractions/ITransactionalStateFactory.cs +++ b/src/Orleans.Transactions/Abstractions/ITransactionalStateFactory.cs @@ -2,15 +2,14 @@ namespace Orleans.Transactions.Abstractions { public class TransactionalStateConfiguration : ITransactionalStateConfiguration { - private readonly string name; private readonly string storage; public TransactionalStateConfiguration(ITransactionalStateConfiguration config, ParticipantId.Role supportedRoles = ParticipantId.Role.Resource | ParticipantId.Role.Manager) { - this.name = config.StateName; + this.StateName = config.StateName; this.storage = config.StorageName; this.SupportedRoles = supportedRoles; } - public string StateName => this.name; + public string StateName { get; } public string StorageName => this.storage; diff --git a/src/Orleans.Transactions/State/StorageBatch.cs b/src/Orleans.Transactions/State/StorageBatch.cs index 6c3a383c36..fb26c104da 100644 --- a/src/Orleans.Transactions/State/StorageBatch.cs +++ b/src/Orleans.Transactions/State/StorageBatch.cs @@ -42,9 +42,6 @@ internal class StorageBatch : ITransactionalStateStorageEvents // follow-up actions, to be executed after storing this batch private readonly List followUpActions; private readonly List>> storeConditions; - - // counters for each type of event - private int total = 0; private int prepare = 0; private int read = 0; private int commit = 0; @@ -56,10 +53,10 @@ internal class StorageBatch : ITransactionalStateStorageEvents public string ETag { get; set; } - public int BatchSize => total; + public int BatchSize { get; private set; } = 0; public override string ToString() { - return $"batchsize={total} [{read}r {prepare}p {commit}c {confirm}cf {collect}cl {cancel}cc]"; + return $"batchsize={BatchSize} [{read}r {prepare}p {commit}c {confirm}cf {collect}cl {cancel}cc]"; } public StorageBatch(TransactionalStateMetaData metaData, string etag, long confirmUpTo, long cancelAbove) @@ -103,7 +100,7 @@ public void RunFollowUpActions() public void Read(DateTime timestamp) { read++; - total++; + BatchSize++; if (MetaData.TimeStamp < timestamp) { @@ -115,7 +112,7 @@ public void Prepare(long sequenceNumber, Guid transactionId, DateTime timestamp, ParticipantId transactionManager, TState state) { prepare++; - total++; + BatchSize++; if (MetaData.TimeStamp < timestamp) MetaData.TimeStamp = timestamp; @@ -138,7 +135,7 @@ public void Prepare(long sequenceNumber, Guid transactionId, DateTime timestamp, public void Cancel(long sequenceNumber) { cancel++; - total++; + BatchSize++; this.prepares.Remove(sequenceNumber); @@ -151,7 +148,7 @@ public void Cancel(long sequenceNumber) public void Confirm(long sequenceNumber) { confirm++; - total++; + BatchSize++; confirmUpTo = sequenceNumber; @@ -174,7 +171,7 @@ public void Confirm(long sequenceNumber) public void Commit(Guid transactionId, DateTime timestamp, List WriteParticipants) { commit++; - total++; + BatchSize++; MetaData.CommitRecords.Add(transactionId, new CommitRecord() { @@ -186,7 +183,7 @@ public void Commit(Guid transactionId, DateTime timestamp, List W public void Collect(Guid transactionId) { collect++; - total++; + BatchSize++; MetaData.CommitRecords.Remove(transactionId); } diff --git a/test/Benchmarks/Serialization/Utilities/ClassSingleSegmentBuffer.cs b/test/Benchmarks/Serialization/Utilities/ClassSingleSegmentBuffer.cs index c52a689eca..1c21b7d3e5 100644 --- a/test/Benchmarks/Serialization/Utilities/ClassSingleSegmentBuffer.cs +++ b/test/Benchmarks/Serialization/Utilities/ClassSingleSegmentBuffer.cs @@ -8,32 +8,31 @@ namespace Benchmarks.Utilities public class ClassSingleSegmentBuffer : IBufferWriter { private readonly byte[] _buffer; - private int _written; public ClassSingleSegmentBuffer(byte[] buffer) { _buffer = buffer; - _written = 0; + Length = 0; } - public void Advance(int bytes) => _written += bytes; + public void Advance(int bytes) => Length += bytes; [Pure] - public Memory GetMemory(int sizeHint = 0) => _buffer.AsMemory(_written); + public Memory GetMemory(int sizeHint = 0) => _buffer.AsMemory(Length); [Pure] - public Span GetSpan(int sizeHint) => _buffer.AsSpan(_written); + public Span GetSpan(int sizeHint) => _buffer.AsSpan(Length); - public byte[] ToArray() => _buffer.AsSpan(0, _written).ToArray(); + public byte[] ToArray() => _buffer.AsSpan(0, Length).ToArray(); - public void Reset() => _written = 0; + public void Reset() => Length = 0; [Pure] - public int Length => _written; + public int Length { get; private set; } [Pure] - public ReadOnlySequence GetReadOnlySequence() => new(_buffer, 0, _written); + public ReadOnlySequence GetReadOnlySequence() => new(_buffer, 0, Length); - public override string ToString() => Encoding.UTF8.GetString(_buffer.AsSpan(0, _written).ToArray()); + public override string ToString() => Encoding.UTF8.GetString(_buffer.AsSpan(0, Length).ToArray()); } } \ No newline at end of file diff --git a/test/Benchmarks/Serialization/Utilities/SingleSegmentBuffer.cs b/test/Benchmarks/Serialization/Utilities/SingleSegmentBuffer.cs index 5d202dbf6f..ee84d90a7a 100644 --- a/test/Benchmarks/Serialization/Utilities/SingleSegmentBuffer.cs +++ b/test/Benchmarks/Serialization/Utilities/SingleSegmentBuffer.cs @@ -8,32 +8,31 @@ namespace Benchmarks.Utilities public struct SingleSegmentBuffer : IBufferWriter { private readonly byte[] _buffer; - private int _written; public SingleSegmentBuffer(byte[] buffer) { _buffer = buffer; - _written = 0; + Length = 0; } - public void Advance(int bytes) => _written += bytes; + public void Advance(int bytes) => Length += bytes; [Pure] - public Memory GetMemory(int sizeHint = 0) => _buffer.AsMemory(_written); + public Memory GetMemory(int sizeHint = 0) => _buffer.AsMemory(Length); [Pure] - public Span GetSpan(int sizeHint) => _buffer.AsSpan(_written); + public Span GetSpan(int sizeHint) => _buffer.AsSpan(Length); - public byte[] ToArray() => _buffer.AsSpan(0, _written).ToArray(); + public byte[] ToArray() => _buffer.AsSpan(0, Length).ToArray(); - public void Reset() => _written = 0; + public void Reset() => Length = 0; [Pure] - public int Length => _written; + public int Length { get; private set; } [Pure] - public ReadOnlySpan GetReadOnlySpan() => new(_buffer, 0, _written); + public ReadOnlySpan GetReadOnlySpan() => new(_buffer, 0, Length); - public override string ToString() => Encoding.UTF8.GetString(_buffer.AsSpan(0, _written).ToArray()); + public override string ToString() => Encoding.UTF8.GetString(_buffer.AsSpan(0, Length).ToArray()); } } \ No newline at end of file diff --git a/test/DefaultCluster.Tests/CodeGenTests/IRuntimeCodeGenGrain.cs b/test/DefaultCluster.Tests/CodeGenTests/IRuntimeCodeGenGrain.cs index 5c490c6afe..eee7b0d78a 100644 --- a/test/DefaultCluster.Tests/CodeGenTests/IRuntimeCodeGenGrain.cs +++ b/test/DefaultCluster.Tests/CodeGenTests/IRuntimeCodeGenGrain.cs @@ -157,8 +157,6 @@ public class GenericGrainState [GenerateSerializer] public class @event : IEquatable<@event> { - private static readonly IEqualityComparer<@event> EventComparerInstance = new EventEqualityComparer(); - public enum @enum { @async, @@ -195,13 +193,7 @@ public enum @enum [Id(4)] public List<@event> @if { get; set; } - public static IEqualityComparer<@event> EventComparer - { - get - { - return EventComparerInstance; - } - } + public static IEqualityComparer<@event> EventComparer { get; } = new EventEqualityComparer(); /// /// Gets or sets the private id. diff --git a/test/Extensions/TesterAzureUtils/Utilities/AsyncPipeline.cs b/test/Extensions/TesterAzureUtils/Utilities/AsyncPipeline.cs index 4db3db6f09..85ce770df3 100644 --- a/test/Extensions/TesterAzureUtils/Utilities/AsyncPipeline.cs +++ b/test/Extensions/TesterAzureUtils/Utilities/AsyncPipeline.cs @@ -21,14 +21,13 @@ public class AsyncPipeline public const int DEFAULT_CAPACITY = 10; private readonly HashSet running; - private readonly int capacity; private readonly LinkedList>> waiting; private readonly object lockable; /// /// The maximal number of async in-flight operations that can be enqueued into this async pipeline. /// - public int Capacity { get { return capacity; } } + public int Capacity { get; } /// /// The number of items currently enqueued into this async pipeline. @@ -52,7 +51,7 @@ public AsyncPipeline(int capacity) throw new ArgumentOutOfRangeException(nameof(capacity), "The pipeline size must be larger than 0."); running = new HashSet(); waiting = new LinkedList>>(); - this.capacity = capacity; + this.Capacity = capacity; lockable = new object(); } @@ -117,7 +116,7 @@ private bool IsFull { get { - return Count >= capacity; + return Count >= Capacity; } } diff --git a/test/Orleans.Serialization.UnitTests/InvokableTestInterfaces.cs b/test/Orleans.Serialization.UnitTests/InvokableTestInterfaces.cs index 093f3c89c4..455996a50d 100644 --- a/test/Orleans.Serialization.UnitTests/InvokableTestInterfaces.cs +++ b/test/Orleans.Serialization.UnitTests/InvokableTestInterfaces.cs @@ -251,8 +251,6 @@ public class GenericGrainState [GenerateSerializer] public class @event : IEquatable<@event> { - private static readonly IEqualityComparer<@event> EventComparerInstance = new EventEqualityComparer(); - public enum @enum { @async, @@ -289,13 +287,7 @@ public enum @enum [Id(4)] public List<@event> @if { get; set; } - public static IEqualityComparer<@event> EventComparer - { - get - { - return EventComparerInstance; - } - } + public static IEqualityComparer<@event> EventComparer { get; } = new EventEqualityComparer(); /// /// Gets or sets the private id. diff --git a/test/TesterInternal/StreamingTests/StreamTestHelperClasses.cs b/test/TesterInternal/StreamingTests/StreamTestHelperClasses.cs index a2df4762af..3220b61cb0 100644 --- a/test/TesterInternal/StreamingTests/StreamTestHelperClasses.cs +++ b/test/TesterInternal/StreamingTests/StreamTestHelperClasses.cs @@ -351,8 +351,6 @@ internal class ProducerProxy { private readonly IStreaming_ProducerGrain[] _targets; private readonly ILogger _logger; - private readonly Guid _streamId; - private readonly string _providerName; private readonly InterlockedFlag _cleanedUpFlag; public Task ExpectedItemsProduced @@ -360,9 +358,9 @@ public Task ExpectedItemsProduced get { return GetExpectedItemsProduced(); } } - public string ProviderName { get { return _providerName; } } + public string ProviderName { get; } - public Guid StreamIdGuid { get { return _streamId; } } + public Guid StreamIdGuid { get; } public StreamId StreamId { get; } @@ -370,8 +368,8 @@ private ProducerProxy(IStreaming_ProducerGrain[] targets, Guid streamId, string { _targets = targets; _logger = logger; - _streamId = streamId; - _providerName = providerName; + StreamIdGuid = streamId; + ProviderName = providerName; _cleanedUpFlag = new InterlockedFlag(); StreamId = StreamId.Create(null, streamId); } From 2dbb08dc35c5098769495e351418bdff8234dbdc Mon Sep 17 00:00:00 2001 From: David Pine Date: Tue, 5 Sep 2023 08:59:53 -0500 Subject: [PATCH 2/3] Revert files per peer review. --- .../IDs/SystemTargetGrainId.cs | 25 ++++++++--------- .../Messaging/PrefixingBufferWriter.cs | 22 ++++++++------- .../Adaptors/BufferSliceReaderInput.cs | 27 ++++++++++--------- .../Buffers/Adaptors/MemoryBufferWriter.cs | 19 ++++++------- .../Buffers/Adaptors/SpanBufferWriter.cs | 17 ++++++------ .../Session/ReferencedObjectCollection.cs | 13 ++++----- .../Common/PooledCache/CachedMessageBlock.cs | 25 ++++++++--------- 7 files changed, 78 insertions(+), 70 deletions(-) diff --git a/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs b/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs index 3de070c52d..a3e321d242 100644 --- a/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs +++ b/src/Orleans.Core.Abstractions/IDs/SystemTargetGrainId.cs @@ -14,6 +14,7 @@ namespace Orleans.Runtime public readonly struct SystemTargetGrainId : IEquatable, IComparable, ISpanFormattable { private const char SegmentSeparator = '+'; + private readonly GrainId _grainId; /// /// Initializes a new instance of the struct. @@ -21,12 +22,12 @@ namespace Orleans.Runtime /// /// The grain id. /// - private SystemTargetGrainId(GrainId grainId) => GrainId = grainId; + private SystemTargetGrainId(GrainId grainId) => _grainId = grainId; /// /// Gets the underlying identity. /// - public GrainId GrainId { get; } + public GrainId GrainId => _grainId; /// /// Creates a new instance. @@ -120,10 +121,10 @@ public static bool TryParse(GrainId grainId, out SystemTargetGrainId systemTarge public SystemTargetGrainId WithSiloAddress(SiloAddress siloAddress) { var addr = siloAddress.ToUtf8String(); - var key = GrainId.Key.AsSpan(); + var key = _grainId.Key.AsSpan(); if (key.IndexOf((byte)SegmentSeparator) is int index && index >= 0) { - var extraIdentifier = key.Slice(index + 1); + var extraIdentifier = key[(index + 1)..]; var buf = new byte[addr.Length + 1 + extraIdentifier.Length]; addr.CopyTo(buf.AsSpan()); @@ -132,7 +133,7 @@ public SystemTargetGrainId WithSiloAddress(SiloAddress siloAddress) addr = buf; } - return new SystemTargetGrainId(new GrainId(GrainId.Type, new IdSpan(addr))); + return new SystemTargetGrainId(new GrainId(_grainId.Type, new IdSpan(addr))); } /// @@ -143,10 +144,10 @@ public SystemTargetGrainId WithSiloAddress(SiloAddress siloAddress) /// public SiloAddress GetSiloAddress() { - var key = GrainId.Key.AsSpan(); + var key = _grainId.Key.AsSpan(); if (key.IndexOf((byte)SegmentSeparator) is int index && index >= 0) { - key = key.Slice(0, index); + key = key[..index]; } return SiloAddress.FromUtf8String(key); @@ -214,24 +215,24 @@ internal static GrainId CreateGrainServiceGrainId(GrainType grainType, SiloAddre public static GrainType CreateGrainType(string name) => GrainType.Create($"{GrainTypePrefix.SystemTargetPrefix}{name}"); /// - public bool Equals(SystemTargetGrainId other) => GrainId.Equals(other.GrainId); + public bool Equals(SystemTargetGrainId other) => _grainId.Equals(other._grainId); /// public override bool Equals(object? obj) => obj is SystemTargetGrainId observer && this.Equals(observer); /// - public override int GetHashCode() => GrainId.GetHashCode(); + public override int GetHashCode() => _grainId.GetHashCode(); /// - public override string ToString() => GrainId.ToString(); + public override string ToString() => _grainId.ToString(); string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => ToString(); bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider) - => ((ISpanFormattable)GrainId).TryFormat(destination, out charsWritten, format, provider); + => ((ISpanFormattable)_grainId).TryFormat(destination, out charsWritten, format, provider); /// - public int CompareTo(SystemTargetGrainId other) => GrainId.CompareTo(other.GrainId); + public int CompareTo(SystemTargetGrainId other) => _grainId.CompareTo(other._grainId); /// /// Compares the provided operands for equality. diff --git a/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs b/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs index a74d2b6d52..2b08f03b8a 100644 --- a/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs +++ b/src/Orleans.Core/Messaging/PrefixingBufferWriter.cs @@ -56,6 +56,8 @@ internal sealed class PrefixingBufferWriter : IBufferWriter, IDisposable /// private Sequence privateWriter; + private int _committedBytes; + /// /// Initializes a new instance of the class. /// @@ -75,7 +77,7 @@ public PrefixingBufferWriter(int prefixSize, int payloadSizeHint, MemoryPool throw new ArgumentOutOfRangeException(nameof(prefixSize)); } - public int CommittedBytes { get; private set; } + public int CommittedBytes => _committedBytes; /// [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -84,7 +86,7 @@ public void Advance(int count) if (privateWriter == null) { advanced += count; - CommittedBytes += count; + _committedBytes += count; } else { @@ -96,7 +98,7 @@ public void Advance(int count) private void AdvancePrivateWriter(int count) { privateWriter.Advance(count); - CommittedBytes += count; + _committedBytes += count; } /// @@ -107,7 +109,7 @@ public Memory GetMemory(int sizeHint = 0) if (prefixMemory.IsEmpty) Initialize(sizeHint); - var res = realMemory.Slice(advanced); + var res = realMemory[advanced..]; if (!res.IsEmpty && (uint)sizeHint <= (uint)res.Length) return res; @@ -122,7 +124,7 @@ public Span GetSpan(int sizeHint = 0) { if (privateWriter == null) { - var res = realMemory.Span.Slice(advanced); + var res = realMemory.Span[advanced..]; if ((uint)sizeHint < (uint)res.Length) return res; } @@ -182,7 +184,7 @@ public void Reset() realMemory = default; innerWriter = null; advanced = 0; - CommittedBytes = 0; + _committedBytes = 0; } public void Dispose() @@ -198,8 +200,8 @@ private void Initialize(int sizeHint) { int sizeToRequest = this.expectedPrefixSize + Math.Max(sizeHint, this.payloadSizeHint); var memory = this.innerWriter.GetMemory(sizeToRequest); - this.prefixMemory = memory.Slice(0, this.expectedPrefixSize); - this.realMemory = memory.Slice(this.expectedPrefixSize); + this.prefixMemory = memory[..this.expectedPrefixSize]; + this.realMemory = memory[this.expectedPrefixSize..]; } /// @@ -350,7 +352,7 @@ private sealed class SequenceSegment : ReadOnlySequenceSegment /// internal int End { get; private set; } - internal Memory TrailingSlack => this.AvailableMemory.Slice(this.End); + internal Memory TrailingSlack => this.AvailableMemory[this.End..]; private IMemoryOwner MemoryOwner; @@ -397,7 +399,7 @@ public void Advance(int count) // If we ever support creating these instances on existing arrays, such that // this.Start isn't 0 at the beginning, we'll have to "pin" this.Start and remove // Advance, forcing Sequence itself to track it, the way Pipe does it internally. - this.Memory = AvailableMemory.Slice(0, value); + this.Memory = AvailableMemory[..value]; this.End = value; static void ThrowNegative() => throw new ArgumentOutOfRangeException( diff --git a/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs b/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs index 6cae24fb70..f9db32c902 100644 --- a/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs +++ b/src/Orleans.Serialization/Buffers/Adaptors/BufferSliceReaderInput.cs @@ -14,6 +14,7 @@ public struct BufferSliceReaderInput private static readonly SequenceSegment FinalSegmentSentinel = new(); private readonly BufferSlice _slice; private SequenceSegment _segment; + private int _position; /// /// Initializes a new instance of the type. @@ -26,12 +27,12 @@ public BufferSliceReaderInput(in BufferSlice slice) } internal readonly PooledBuffer Buffer => _slice._buffer; - internal int Position { get; private set; } + internal readonly int Position => _position; internal readonly int Offset => _slice._offset; internal readonly int Length => _slice._length; internal long PreviousBuffersSize; - internal BufferSliceReaderInput ForkFrom(int position) + internal readonly BufferSliceReaderInput ForkFrom(int position) { var sliced = _slice.Slice(position); return new BufferSliceReaderInput(in sliced); @@ -41,7 +42,7 @@ internal ReadOnlySpan GetNext() { if (ReferenceEquals(_segment, InitialSegmentSentinel)) { - _segment = _slice._buffer._first; + _segment = _slice._buffer.First; } var endPosition = Offset + Length; @@ -51,12 +52,12 @@ internal ReadOnlySpan GetNext() // Find the starting segment and the offset to copy from. int segmentOffset; - if (Position < Offset) + if (_position < Offset) { - if (Position + segment.Length <= Offset) + if (_position + segment.Length <= Offset) { // Start is in a subsequent segment - Position += segment.Length; + _position += segment.Length; _segment = _segment.Next as SequenceSegment; continue; } @@ -71,7 +72,7 @@ internal ReadOnlySpan GetNext() segmentOffset = 0; } - var segmentLength = Math.Min(segment.Length - segmentOffset, endPosition - (Position + segmentOffset)); + var segmentLength = Math.Min(segment.Length - segmentOffset, endPosition - (_position + segmentOffset)); if (segmentLength == 0) { ThrowInsufficientData(); @@ -79,15 +80,15 @@ internal ReadOnlySpan GetNext() } var result = segment.Slice(segmentOffset, segmentLength); - Position += segmentOffset + segmentLength; + _position += segmentOffset + segmentLength; _segment = _segment.Next as SequenceSegment; return result; } - if (_segment != FinalSegmentSentinel && Buffer._currentPosition > 0 && Buffer._writeHead is { } head && Position < endPosition) + if (_segment != FinalSegmentSentinel && Buffer.CurrentPosition > 0 && Buffer.WriteHead is { } head && _position < endPosition) { - var finalOffset = Math.Max(Offset - Position, 0); - var finalLength = Math.Min(Buffer._currentPosition, endPosition - (Position + finalOffset)); + var finalOffset = Math.Max(Offset - _position, 0); + var finalLength = Math.Min(Buffer.CurrentPosition, endPosition - (_position + finalOffset)); if (finalLength == 0) { ThrowInsufficientData(); @@ -95,8 +96,8 @@ internal ReadOnlySpan GetNext() } var result = head.Array.AsSpan(finalOffset, finalLength); - Position += finalOffset + finalLength; - Debug.Assert(Position == endPosition); + _position += finalOffset + finalLength; + Debug.Assert(_position == endPosition); _segment = FinalSegmentSentinel; return result; } diff --git a/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs b/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs index 17af2490c3..0dcf89a451 100644 --- a/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs +++ b/src/Orleans.Serialization/Buffers/Adaptors/MemoryBufferWriter.cs @@ -9,6 +9,7 @@ namespace Orleans.Serialization.Buffers.Adaptors public struct MemoryBufferWriter : IBufferWriter { private readonly Memory _buffer; + private int _bytesWritten; /// /// Initializes a new instance of the struct. @@ -17,50 +18,50 @@ public struct MemoryBufferWriter : IBufferWriter internal MemoryBufferWriter(Memory buffer) { _buffer = buffer; - BytesWritten = 0; + _bytesWritten = 0; } /// /// Gets the number of bytes written. /// /// The number of bytes written. - public int BytesWritten { get; private set; } + public readonly int BytesWritten => _bytesWritten; /// public void Advance(int count) { - if (BytesWritten > _buffer.Length) + if (_bytesWritten > _buffer.Length) { ThrowInvalidCount(); static void ThrowInvalidCount() => throw new InvalidOperationException("Cannot advance past the end of the buffer"); } - BytesWritten += count; + _bytesWritten += count; } /// public Memory GetMemory(int sizeHint = 0) { - if (BytesWritten + sizeHint >= _buffer.Length) + if (_bytesWritten + sizeHint >= _buffer.Length) { ThrowInsufficientCapacity(sizeHint); } - return _buffer.Slice(BytesWritten); + return _buffer[_bytesWritten..]; } /// public Span GetSpan(int sizeHint = 0) { - if (BytesWritten + sizeHint >= _buffer.Length) + if (_bytesWritten + sizeHint >= _buffer.Length) { ThrowInsufficientCapacity(sizeHint); } - return _buffer.Span.Slice(BytesWritten); + return _buffer.Span[_bytesWritten..]; } - private void ThrowInsufficientCapacity(int sizeHint) => throw new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_buffer.Length}. Current length is {BytesWritten} and requested size increase is {sizeHint}"); + private void ThrowInsufficientCapacity(int sizeHint) => throw new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_buffer.Length}. Current length is {_bytesWritten} and requested size increase is {sizeHint}"); } } diff --git a/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs b/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs index 50783f797a..79e6cc7744 100644 --- a/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs +++ b/src/Orleans.Serialization/Buffers/Adaptors/SpanBufferWriter.cs @@ -9,6 +9,7 @@ namespace Orleans.Serialization.Buffers.Adaptors public struct SpanBufferWriter : IBufferWriter { private readonly int _maxLength; + private int _bytesWritten; /// /// Initializes a new instance of the struct. @@ -17,28 +18,28 @@ public struct SpanBufferWriter : IBufferWriter internal SpanBufferWriter(Span buffer) { _maxLength = buffer.Length; - BytesWritten = 0; + _bytesWritten = 0; } /// /// Gets the number of bytes written. /// /// The number of bytes written. - public int BytesWritten { get; private set; } + public readonly int BytesWritten => _bytesWritten; /// - public void Advance(int count) => BytesWritten += count; + public void Advance(int count) => _bytesWritten += count; /// - public Memory GetMemory(int sizeHint = 0) => throw GetException(sizeHint); + public readonly Memory GetMemory(int sizeHint = 0) => throw GetException(sizeHint); /// - public Span GetSpan(int sizeHint = 0) => throw GetException(sizeHint); + public readonly Span GetSpan(int sizeHint = 0) => throw GetException(sizeHint); - private Exception GetException(int sizeHint) + private readonly Exception GetException(int sizeHint) { - return BytesWritten + sizeHint > _maxLength - ? new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_maxLength}. Current length is {BytesWritten} and requested size increase is {sizeHint}") + return _bytesWritten + sizeHint > _maxLength + ? new InvalidOperationException($"Insufficient capacity to perform the requested operation. Buffer size is {_maxLength}. Current length is {_bytesWritten} and requested size increase is {sizeHint}") : new NotSupportedException("Method is not supported on this instance"); } } diff --git a/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs b/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs index c6c4aaaedb..7066806f21 100644 --- a/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs +++ b/src/Orleans.Serialization/Session/ReferencedObjectCollection.cs @@ -41,6 +41,7 @@ public ReferencePair(uint id, object @object) private Dictionary _referenceToObjectOverflow; private Dictionary _objectToReferenceOverflow; + private uint _currentReferenceId; /// /// Tries to get the referenced object with the specified id. @@ -66,9 +67,9 @@ public object TryGetReferencedObject(uint reference) /// Marks a value field. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void MarkValueField() => ++CurrentReferenceId; + public void MarkValueField() => ++_currentReferenceId; - internal uint CreateRecordPlaceholder() => ++CurrentReferenceId; + internal uint CreateRecordPlaceholder() => ++_currentReferenceId; /// /// Gets or adds a reference. @@ -80,7 +81,7 @@ public object TryGetReferencedObject(uint reference) public bool GetOrAddReference(object value, out uint reference) { // Unconditionally bump the reference counter since a call to this method signifies a potential reference. - var nextReference = ++CurrentReferenceId; + var nextReference = ++_currentReferenceId; // Null is always at reference 0 if (value is null) @@ -182,7 +183,7 @@ private void CreateObjectToReferenceOverflow(object value) objects[i] = default; } - result[value] = CurrentReferenceId; + result[value] = _currentReferenceId; _objectToReferenceCount = 0; _objectToReferenceOverflow = result; @@ -261,7 +262,7 @@ void CreateReferenceToObjectOverflow() /// /// The value. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void RecordReferenceField(object value) => RecordReferenceField(value, ++CurrentReferenceId); + public void RecordReferenceField(object value) => RecordReferenceField(value, ++_currentReferenceId); /// /// Records a reference field with the specified identifier. @@ -295,7 +296,7 @@ public void RecordReferenceField(object value, uint referenceId) /// Gets or sets the current reference identifier. /// /// The current reference identifier. - public uint CurrentReferenceId { get; set; } + public uint CurrentReferenceId { get => _currentReferenceId; set => _currentReferenceId = value; } /// /// Resets this instance. diff --git a/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs b/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs index 10e3a3d957..b7522bcf8f 100644 --- a/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs +++ b/src/Orleans.Streaming/Common/PooledCache/CachedMessageBlock.cs @@ -19,6 +19,7 @@ public class CachedMessageBlock : PooledResource private readonly CachedMessage[] cachedMessages; private readonly int blockSize; private int writeIndex; + private int readIndex; /// /// Linked list node, so this message block can be kept in a linked list. @@ -33,7 +34,7 @@ public class CachedMessageBlock : PooledResource /// /// Gets a value indicating whether this block is empty. /// - public bool IsEmpty => OldestMessageIndex >= writeIndex; + public bool IsEmpty => readIndex >= writeIndex; /// /// Gets the index of most recent message added to the block. @@ -43,7 +44,7 @@ public class CachedMessageBlock : PooledResource /// /// Gets the index of the oldest message in this block. /// - public int OldestMessageIndex { get; private set; } + public int OldestMessageIndex => readIndex; /// /// Gets the oldest message in the block. @@ -60,7 +61,7 @@ public class CachedMessageBlock : PooledResource /// public int ItemCount { get { - int count = writeIndex - OldestMessageIndex; + int count = writeIndex - readIndex; return count >= 0 ? count : 0; } } @@ -74,7 +75,7 @@ public CachedMessageBlock(int blockSize = DefaultCachedMessagesPerBlock) this.blockSize = blockSize; cachedMessages = new CachedMessage[blockSize]; writeIndex = 0; - OldestMessageIndex = 0; + readIndex = 0; Node = new LinkedListNode(this); } @@ -84,9 +85,9 @@ public CachedMessageBlock(int blockSize = DefaultCachedMessagesPerBlock) /// if there are more items remaining; otherwise . public bool Remove() { - if (OldestMessageIndex < writeIndex) + if (readIndex < writeIndex) { - OldestMessageIndex++; + readIndex++; return true; } return false; @@ -119,7 +120,7 @@ public CachedMessage this[int index] { get { - if (index >= writeIndex || index < OldestMessageIndex) + if (index >= writeIndex || index < readIndex) { throw new ArgumentOutOfRangeException(nameof(index)); } @@ -135,7 +136,7 @@ public CachedMessage this[int index] /// The sequence token. public StreamSequenceToken GetSequenceToken(int index, ICacheDataAdapter dataAdapter) { - if (index >= writeIndex || index < OldestMessageIndex) + if (index >= writeIndex || index < readIndex) { throw new ArgumentOutOfRangeException(nameof(index)); } @@ -169,7 +170,7 @@ public StreamSequenceToken GetOldestSequenceToken(ICacheDataAdapter dataAdapter) /// The index of the first message in this block that has a sequence token equal to or before the provided token. public int GetIndexOfFirstMessageLessThanOrEqualTo(StreamSequenceToken token) { - for (int i = writeIndex - 1; i >= OldestMessageIndex; i--) + for (int i = writeIndex - 1; i >= readIndex; i--) { if (cachedMessages[i].Compare(token) <= 0) { @@ -188,7 +189,7 @@ public int GetIndexOfFirstMessageLessThanOrEqualTo(StreamSequenceToken token) /// if the message was found, otherwise. public bool TryFindFirstMessage(StreamId streamId, ICacheDataAdapter dataAdapter, out int index) { - return TryFindNextMessage(OldestMessageIndex, streamId, dataAdapter, out index); + return TryFindNextMessage(readIndex, streamId, dataAdapter, out index); } /// @@ -201,7 +202,7 @@ public bool TryFindFirstMessage(StreamId streamId, ICacheDataAdapter dataAdapter /// if the message was found, otherwise. public bool TryFindNextMessage(int start, StreamId streamId, ICacheDataAdapter dataAdapter, out int index) { - if (start < OldestMessageIndex) + if (start < readIndex) { throw new ArgumentOutOfRangeException(nameof(start)); } @@ -223,7 +224,7 @@ public bool TryFindNextMessage(int start, StreamId streamId, ICacheDataAdapter d public override void OnResetState() { writeIndex = 0; - OldestMessageIndex = 0; + readIndex = 0; } } } From 1a7399c79e7af7a997567c9fbd4139218e71b0f5 Mon Sep 17 00:00:00 2001 From: David Pine Date: Thu, 14 Sep 2023 06:52:51 -0500 Subject: [PATCH 3/3] Apply suggestions from code review --- src/AdoNet/Shared/Storage/RelationalStorage.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AdoNet/Shared/Storage/RelationalStorage.cs b/src/AdoNet/Shared/Storage/RelationalStorage.cs index e1aa08834e..dfe02505d5 100644 --- a/src/AdoNet/Shared/Storage/RelationalStorage.cs +++ b/src/AdoNet/Shared/Storage/RelationalStorage.cs @@ -247,7 +247,7 @@ private async Task, int>> ExecuteAsync( CommandBehavior commandBehavior, CancellationToken cancellationToken) { - using (var connection = DbConnectionFactory.CreateConnection(invariantName, ConnectionString)) + using (var connection = DbConnectionFactory.CreateConnection(_invariantName, ConnectionString)) { await connection.OpenAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); using (var command = connection.CreateCommand())