- 
                Notifications
    
You must be signed in to change notification settings  - Fork 2.1k
 
Update Protobuf Serializer #8334
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 2 commits
      Commits
    
    
            Show all changes
          
          
            6 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      c9b283b
              
                Refactored Orleans.Serialization.Protobuf
              
              
                larsfjerm bdb2cf4
              
                Update ProtobufCodec.cs
              
              
                larsfjerm a7c4c9b
              
                rm ProtobufNet
              
              
                larsfjerm 8229773
              
                Add ProtobufSerializerTests
              
              
                larsfjerm 3c04242
              
                Update ProtobufSerializerTests.cs
              
              
                larsfjerm 848c133
              
                Merge remote-tracking branch 'upstream/main'
              
              
                larsfjerm File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            18 changes: 9 additions & 9 deletions
          
          18 
        
  src/Serializers/Orleans.Serialization.Protobuf/Orleans.Serialization.Protobuf.csproj
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -1,20 +1,20 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <PackageId>Microsoft.Orleans.OrleansGoogleUtils</PackageId> | ||
| <Title>Microsoft Orleans Google Utilities</Title> | ||
| <Description>Library of utility types for Google of Microsoft Orleans.</Description> | ||
| <PackageTags>$(PackageTags) ProtoBuf</PackageTags> | ||
| <TargetFrameworks>$(DefaultTargetFrameworks)</TargetFrameworks> | ||
| </PropertyGroup> | ||
| 
     | 
||
| <PropertyGroup> | ||
| <AssemblyName>Orleans.Serialization.Protobuf</AssemblyName> | ||
| <RootNamespace>OrleansGoogleUtils</RootNamespace> | ||
| <PackageId>Microsoft.Orleans.Serialization.Protobuf</PackageId> | ||
| <TargetFrameworks>$(DefaultTargetFrameworks);netstandard2.1</TargetFrameworks> | ||
| <PackageDescription>Google.Protobuf integration for Orleans.Serialization</PackageDescription> | ||
| <OrleansBuildTimeCodeGen>true</OrleansBuildTimeCodeGen> | ||
| <IsOrleansFrameworkPart>false</IsOrleansFrameworkPart> | ||
| </PropertyGroup> | ||
| 
     | 
||
| <ItemGroup> | ||
| <PackageReference Include="Google.Protobuf" Version="$(GoogleProtobufVersion)" /> | ||
| <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> | ||
| </ItemGroup> | ||
| 
     | 
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\Orleans.Serialization\Orleans.Serialization.csproj" /> | ||
| </ItemGroup> | ||
| 
     | 
||
| </Project> | ||
        
          
          
            210 changes: 210 additions & 0 deletions
          
          210 
        
  src/Serializers/Orleans.Serialization.Protobuf/ProtobufCodec.cs
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| using Google.Protobuf; | ||
| using Orleans.Serialization.Buffers; | ||
| using Orleans.Serialization.Buffers.Adaptors; | ||
| using Orleans.Serialization.Cloning; | ||
| using Orleans.Serialization.Codecs; | ||
| using Orleans.Serialization.Serializers; | ||
| using Orleans.Serialization.WireProtocol; | ||
| using System; | ||
| using System.Collections.Concurrent; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Reflection; | ||
| 
     | 
||
| namespace Orleans.Serialization; | ||
| 
     | 
||
| [Alias(WellKnownAlias)] | ||
| public sealed class ProtobufCodec : IGeneralizedCodec, IGeneralizedCopier, ITypeFilter | ||
| { | ||
| public const string WellKnownAlias = "protobuf"; | ||
| 
     | 
||
| private static readonly ConcurrentDictionary<RuntimeTypeHandle, MessageParser> Parsers = new(); | ||
| 
     | 
||
| private readonly ICodecSelector[] _serializableTypeSelectors; | ||
| private readonly ICopierSelector[] _copyableTypeSelectors; | ||
| 
     | 
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="ProtobufCodec"/> class. | ||
| /// </summary> | ||
| /// <param name="serializableTypeSelectors">Filters used to indicate which types should be serialized by this codec.</param> | ||
| /// <param name="copyableTypeSelectors">Filters used to indicate which types should be copied by this codec.</param> | ||
| public ProtobufCodec( | ||
| IEnumerable<ICodecSelector> serializableTypeSelectors, | ||
| IEnumerable<ICopierSelector> copyableTypeSelectors) | ||
| { | ||
| _serializableTypeSelectors = serializableTypeSelectors.Where(t => string.Equals(t.CodecName, WellKnownAlias, StringComparison.Ordinal)).ToArray(); | ||
| _copyableTypeSelectors = copyableTypeSelectors.Where(t => string.Equals(t.CopierName, WellKnownAlias, StringComparison.Ordinal)).ToArray(); | ||
| } | ||
| 
     | 
||
| public object DeepCopy(object input, CopyContext context) | ||
| { | ||
| if (!context.TryGetCopy(input, out object result)) | ||
| { | ||
| dynamic dynamicSource = input; | ||
| result = dynamicSource.Clone(); | ||
| 
     | 
||
| context.RecordCopy(input, result); | ||
                
      
                  larsfjerm marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| } | ||
| 
     | 
||
| return result; | ||
| } | ||
| 
     | 
||
| /// <inheritdoc/> | ||
| bool IGeneralizedCodec.IsSupportedType(Type type) | ||
| { | ||
| foreach (var selector in _serializableTypeSelectors) | ||
| { | ||
| if (selector.IsSupportedType(type)) | ||
| { | ||
| return IsMessageParser(type); | ||
| } | ||
| } | ||
| 
     | 
||
| return false; | ||
| } | ||
| 
     | 
||
| /// <inheritdoc/> | ||
| bool IGeneralizedCopier.IsSupportedType(Type type) | ||
| { | ||
| foreach (var selector in _copyableTypeSelectors) | ||
| { | ||
| if (selector.IsSupportedType(type)) | ||
| { | ||
| return IsMessageParser(type); | ||
| } | ||
| } | ||
| 
     | 
||
| return false; | ||
| } | ||
| 
     | 
||
| /// <inheritdoc/> | ||
| bool? ITypeFilter.IsTypeAllowed(Type type) | ||
| { | ||
| if (!typeof(IMessage).IsAssignableFrom(type)) | ||
| { | ||
| return null; | ||
| } | ||
| 
     | 
||
| return ((IGeneralizedCodec)this).IsSupportedType(type) || ((IGeneralizedCopier)this).IsSupportedType(type); | ||
| } | ||
| 
     | 
||
| static bool IsMessageParser(Type type) | ||
| { | ||
| if (!Parsers.ContainsKey(type.TypeHandle)) | ||
| { | ||
| var prop = type.GetProperty("Parser", BindingFlags.Public | BindingFlags.Static); | ||
                
      
                  larsfjerm marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| if (prop is null) | ||
| { | ||
| return false; | ||
| } | ||
| 
     | 
||
| if (prop.GetValue(null, null) is not MessageParser parser) | ||
| { | ||
| throw new ArgumentNullException(nameof(parser)); | ||
| } | ||
| 
     | 
||
| Parsers.TryAdd(type.TypeHandle, parser); | ||
| } | ||
| 
     | 
||
| return true; | ||
| } | ||
| 
     | 
||
| /// <inheritdoc/> | ||
| object IFieldCodec.ReadValue<TInput>(ref Reader<TInput> reader, Field field) | ||
| { | ||
| if (field.IsReference) | ||
| { | ||
| return ReferenceCodec.ReadReference(ref reader, field.FieldType); | ||
| } | ||
| 
     | 
||
| field.EnsureWireTypeTagDelimited(); | ||
| 
     | 
||
| if (!Parsers.TryGetValue(field.FieldType.TypeHandle, out var parser)) | ||
| { | ||
| throw new ArgumentException($"No parser found for the expected type {field.FieldType}", nameof(TInput)); | ||
| } | ||
| 
     | 
||
| var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session); | ||
| object result = null; | ||
| Type type = null; | ||
| uint fieldId = 0; | ||
| 
     | 
||
| while (true) | ||
| { | ||
| var header = reader.ReadFieldHeader(); | ||
| if (header.IsEndBaseOrEndObject) | ||
| { | ||
| break; | ||
| } | ||
| 
     | 
||
| fieldId += header.FieldIdDelta; | ||
| switch (fieldId) | ||
| { | ||
| case 0: | ||
| ReferenceCodec.MarkValueField(reader.Session); | ||
| type = reader.Session.TypeCodec.ReadLengthPrefixed(ref reader); | ||
| break; | ||
| case 1: | ||
| if (type is null) | ||
| { | ||
| ThrowTypeFieldMissing(); | ||
| } | ||
| 
     | 
||
| ReferenceCodec.MarkValueField(reader.Session); | ||
| var length = (int)reader.ReadVarUInt32(); | ||
| 
     | 
||
| using (var buffer = new PooledArrayBufferWriter()) | ||
| { | ||
| var spanBuffer = buffer.GetSpan(length)[..length]; | ||
| reader.ReadBytes(spanBuffer); | ||
| result = parser.ParseFrom(spanBuffer); | ||
| } | ||
| break; | ||
| default: | ||
| reader.ConsumeUnknownField(header); | ||
| break; | ||
| } | ||
| } | ||
| 
     | 
||
| ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId); | ||
| return result; | ||
| } | ||
| 
     | 
||
| private static void ThrowTypeFieldMissing() => throw new RequiredFieldMissingException("Serialized value is missing its type field."); | ||
| 
     | 
||
| /// <inheritdoc/> | ||
| void IFieldCodec.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, object value) | ||
| { | ||
| if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) | ||
| { | ||
| return; | ||
| } | ||
| 
     | 
||
| if (value is not IMessage protobufMessage) | ||
| { | ||
| throw new ArgumentException("The provided value for serialization in not an instance of IMessage"); | ||
| } | ||
| 
     | 
||
| writer.WriteFieldHeader(fieldIdDelta, expectedType, protobufMessage.GetType(), WireType.TagDelimited); | ||
| 
     | 
||
| // Write the type name | ||
| ReferenceCodec.MarkValueField(writer.Session); | ||
| writer.WriteFieldHeaderExpected(0, WireType.LengthPrefixed); | ||
| writer.Session.TypeCodec.WriteLengthPrefixed(ref writer, value.GetType()); | ||
| 
     | 
||
| var messageSize = protobufMessage.CalculateSize(); | ||
| 
     | 
||
| using var buffer = new PooledArrayBufferWriter(); | ||
| var spanBuffer = buffer.GetSpan(messageSize)[..messageSize]; | ||
| 
     | 
||
| // Write the serialized payload | ||
| protobufMessage.WriteTo(spanBuffer); | ||
| 
     | 
||
| ReferenceCodec.MarkValueField(writer.Session); | ||
| writer.WriteFieldHeaderExpected(1, WireType.LengthPrefixed); | ||
| writer.WriteVarUInt32((uint)spanBuffer.Length); | ||
| writer.Write(spanBuffer); | ||
| 
     | 
||
| writer.WriteEndObject(); | ||
| } | ||
| } | ||
        
          
          
            118 changes: 0 additions & 118 deletions
          
          118 
        
  src/Serializers/Orleans.Serialization.Protobuf/ProtobufSerializer.cs
  
  
      
      
   
        
      
      
    This file was deleted.
      
      Oops, something went wrong.
      
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.