예제 #1
0
        //[Benchmark]
        public object OrleansClassRoundTrip()
        {
            var writer = new BinaryTokenStreamWriter();

            this.orleansSerializer.Serialize(this.value, writer);
            return(this.orleansSerializer.Deserialize(new BinaryTokenStreamReader(writer.ToBytes())));
        }
예제 #2
0
        public void UniqueKeySerializationShouldReproduceAnIdenticalObject()
        {
            {
                var expected = UniqueKey.NewKey(Guid.NewGuid());
                BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
                writer.Write(expected);
                BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
                var actual = reader.ReadUniqueKey();
                Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #1).
            }

            {
                var kx       = random.Next().ToString(CultureInfo.InvariantCulture);
                var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx);
                BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
                writer.Write(expected);
                BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
                var actual = reader.ReadUniqueKey();
                Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #2).
            }

            {
                var kx       = random.Next().ToString(CultureInfo.InvariantCulture) + new String('*', 400);
                var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx);
                BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
                writer.Write(expected);
                BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
                var actual = reader.ReadUniqueKey();
                Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #3).
            }
        }
예제 #3
0
        public ComplexTypeBenchmarks()
        {
            _orleansSerializer = new ClientBuilder()
                                 .ConfigureDefaults()
                                 .UseLocalhostClustering()
                                 .ConfigureServices(s => s.ToList().ForEach(r =>
            {
                if (r.ServiceType == typeof(IConfigurationValidator))
                {
                    _ = s.Remove(r);
                }
            }))
                                 .Configure <ClusterOptions>(o => o.ClusterId = o.ServiceId = "test")
                                 .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(SimpleClass).Assembly).WithCodeGeneration())
                                 .Build().ServiceProvider.GetRequiredService <SerializationManager>();
            var services = new ServiceCollection();

            _ = services
                .AddHagar(hagar => hagar.AddISerializableSupport().AddAssembly(typeof(Program).Assembly));
            var serviceProvider = services.BuildServiceProvider();

            _hagarSerializer  = serviceProvider.GetRequiredService <Serializer <ComplexClass> >();
            _structSerializer = serviceProvider.GetRequiredService <Serializer <SimpleStruct> >();
            _sessionPool      = serviceProvider.GetRequiredService <SerializerSessionPool>();
            _value            = new ComplexClass
            {
                BaseInt = 192,
                Int     = 501,
                String  = "bananas",
                //Array = Enumerable.Range(0, 60).ToArray(),
                //MultiDimensionalArray = new[,] {{0, 2, 4}, {1, 5, 6}}
            };
            _value.AlsoSelf = _value.BaseSelf = _value.Self = _value;

            _structValue = new SimpleStruct
            {
                Int  = 42,
                Bool = true,
                Guid = Guid.NewGuid()
            };
            _session = _sessionPool.GetSession();
            var writer = HagarBuffer.CreateWriter(_session);

            _hagarSerializer.Serialize(_value, ref writer);
            var bytes = new byte[writer.Output.GetMemory().Length];

            writer.Output.GetReadOnlySequence().CopyTo(bytes);
            _hagarBytes = new ReadOnlySequence <byte>(bytes);
            HagarBuffer.Reset();

            var writer2 = new BinaryTokenStreamWriter();

            _orleansSerializer.Serialize(_value, writer2);
            _orleansBytes = writer2.ToBytes();

            _readBytesLength = Math.Min(bytes.Length, _orleansBytes.Sum(x => x.Count));
        }
예제 #4
0
        private GrainReference RoundTripGrainReferenceOrleansSerializer(GrainReference input)
        {
            BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();

            GrainReference.SerializeGrainReference(input, writer, typeof(GrainReference));
            BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
            GrainReference          output = (GrainReference)GrainReference.DeserializeGrainReference(typeof(GrainReference), reader);

            return(output);
        }
예제 #5
0
        private List <ArraySegment <byte> > Serialize_Impl(bool batching, out int headerLengthOut, out int bodyLengthOut)
        {
            var headerStream = new BinaryTokenStreamWriter();

            lock (headers) // Guard against any attempts to modify message headers while we are serializing them
            {
                SerializationManager.SerializeMessageHeaders(headers, headerStream);
            }

            if (bodyBytes == null)
            {
                var bodyStream = new BinaryTokenStreamWriter();
                SerializationManager.Serialize(bodyObject, bodyStream);
                // We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
                // being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
                // serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
                // pretty high (an array allocation plus a bunch of copying).
                bodyBytes = bodyStream.ToBytes() as List <ArraySegment <byte> >;
            }

            if (headerBytes != null)
            {
                BufferPool.GlobalPool.Release(headerBytes);
            }
            headerBytes = headerStream.ToBytes() as List <ArraySegment <byte> >;
            int headerLength = headerBytes.Sum(ab => ab.Count);
            int bodyLength   = bodyBytes.Sum(ab => ab.Count);

            var bytes = new List <ArraySegment <byte> >();

            if (!batching)
            {
                bytes.Add(new ArraySegment <byte>(BitConverter.GetBytes(headerLength)));
                bytes.Add(new ArraySegment <byte>(BitConverter.GetBytes(bodyLength)));
            }
            bytes.AddRange(headerBytes);
            bytes.AddRange(bodyBytes);

            if (headerLength + bodyLength > LargeMessageSizeThreshold)
            {
                logger.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}",
                            headerLength + bodyLength + LENGTH_HEADER_SIZE, headerLength, bodyLength, bytes.Count, this.ToString());
                if (logger.IsVerbose3)
                {
                    logger.Verbose3("Sending large message {0}", this.ToLongString());
                }
            }

            headerLengthOut = headerLength;
            bodyLengthOut   = bodyLength;
            return(bytes);
        }
예제 #6
0
        public ComplexTypeBenchmarks()
        {
            this.orleansSerializer = new ClientBuilder()
                                     .ConfigureDefaults()
                                     .UseLocalhostClustering()
                                     .Configure <ClusterOptions>(o => o.ClusterId = o.ServiceId = "test")
                                     .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(SimpleClass).Assembly).WithCodeGeneration())
                                     .Build().ServiceProvider.GetRequiredService <SerializationManager>();
            var services = new ServiceCollection();

            services
            .AddHagar()
            .AddISerializableSupport()
            .AddSerializers(typeof(Program).Assembly);
            var serviceProvider = services.BuildServiceProvider();

            this.hagarSerializer  = serviceProvider.GetRequiredService <Serializer <ComplexClass> >();
            this.structSerializer = serviceProvider.GetRequiredService <Serializer <SimpleStruct> >();
            this.sessionPool      = serviceProvider.GetRequiredService <SessionPool>();
            this.value            = new ComplexClass
            {
                BaseInt = 192,
                Int     = 501,
                String  = "bananas",
                //Array = Enumerable.Range(0, 60).ToArray(),
                //MultiDimensionalArray = new[,] {{0, 2, 4}, {1, 5, 6}}
            };
            this.value.AlsoSelf = this.value.BaseSelf = this.value.Self = this.value;

            this.structValue = new SimpleStruct
            {
                Int  = 42,
                Bool = true,
                Guid = Guid.NewGuid()
            };
            this.session = sessionPool.GetSession();
            var writer = new Writer(HagarBuffer);

            this.hagarSerializer.Serialize(this.value, session, ref writer);
            var bytes = new byte[HagarBuffer.GetMemory().Length];

            HagarBuffer.GetReadOnlySequence().CopyTo(bytes);
            this.hagarBytes = new ReadOnlySequence <byte>(bytes);
            HagarBuffer.Reset();

            var writer2 = new BinaryTokenStreamWriter();

            this.orleansSerializer.Serialize(this.value, writer2);
            this.orleansBytes = writer2.ToBytes();

            this.readBytesLength = Math.Min(bytes.Length, orleansBytes.Sum(x => x.Count));
        }
예제 #7
0
        private List <ArraySegment <byte> > Serialize_Impl(out int headerLengthOut, out int bodyLengthOut)
        {
            var context = new SerializationContext(RuntimeClient.Current.InternalGrainFactory)
            {
                StreamWriter = new BinaryTokenStreamWriter()
            };

            SerializationManager.SerializeMessageHeaders(Headers, context);

            if (bodyBytes == null)
            {
                var bodyStream = new BinaryTokenStreamWriter();
                SerializationManager.Serialize(bodyObject, bodyStream);
                // We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
                // being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
                // serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
                // pretty high (an array allocation plus a bunch of copying).
                bodyBytes = bodyStream.ToBytes();
            }

            if (headerBytes != null)
            {
                BufferPool.GlobalPool.Release(headerBytes);
            }
            headerBytes = context.StreamWriter.ToBytes();
            int headerLength = context.StreamWriter.CurrentOffset;
            int bodyLength   = BufferLength(bodyBytes);

            var bytes = new List <ArraySegment <byte> >();

            bytes.Add(new ArraySegment <byte>(BitConverter.GetBytes(headerLength)));
            bytes.Add(new ArraySegment <byte>(BitConverter.GetBytes(bodyLength)));

            bytes.AddRange(headerBytes);
            bytes.AddRange(bodyBytes);

            if (headerLength + bodyLength > LargeMessageSizeThreshold)
            {
                logger.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}",
                            headerLength + bodyLength + LENGTH_HEADER_SIZE, headerLength, bodyLength, bytes.Count, this.ToString());
                if (logger.IsVerbose3)
                {
                    logger.Verbose3("Sending large message {0}", this.ToLongString());
                }
            }

            headerLengthOut = headerLength;
            bodyLengthOut   = bodyLength;
            return(bytes);
        }
예제 #8
0
        public void Serialize_CustomSerializer()
        {
            var original = new ClassWithCustomSerializer()
            {
                IntProperty = -3, StringProperty = "Goodbye"
            };
            var writeStream = new BinaryTokenStreamWriter();

            this.fixture.SerializationManager.Serialize(original, writeStream);
            Assert.Equal(1, ClassWithCustomSerializer.SerializeCounter); //Custom serializer was not called

            var readStream = new BinaryTokenStreamReader(writeStream.ToBytes());
            var obj        = this.fixture.SerializationManager.Deserialize(readStream);

            Assert.Equal(1, ClassWithCustomSerializer.DeserializeCounter); //Custom deserializer was not called
        }
예제 #9
0
        static DeserializeBenchmark()
        {
            ProtoInput = new MemoryStream();
            ProtoBuf.Serializer.Serialize(ProtoInput, IntClass.Create());

            HyperionInput = new MemoryStream();
            HyperionSerializer.Serialize(IntClass.Create(), HyperionInput);

            // Hagar
            var services = new ServiceCollection()
                           .AddHagar(hagar => hagar.AddAssembly(typeof(Program).Assembly))
                           .BuildServiceProvider();

            HagarSerializer = services.GetRequiredService <Serializer <IntClass> >();
            var bytes = new byte[1000];

            Session = services.GetRequiredService <SessionPool>().GetSession();
            var writer = new SingleSegmentBuffer(bytes).CreateWriter(Session);

            HagarSerializer.Serialize(ref writer, IntClass.Create());
            HagarInput = bytes;

            // Orleans
            OrleansSerializer = new ClientBuilder()
                                .ConfigureDefaults()
                                .UseLocalhostClustering()
                                .ConfigureServices(s => s.ToList().ForEach(r =>
            {
                if (r.ServiceType == typeof(IConfigurationValidator))
                {
                    s.Remove(r);
                }
            }))
                                .Configure <ClusterOptions>(o => o.ClusterId = o.ServiceId = "test")
                                .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(SimpleClass).Assembly).WithCodeGeneration())
                                .Configure <SerializationProviderOptions>(options => options.FallbackSerializationProvider = typeof(SupportsNothingSerializer).GetTypeInfo())
                                .Build().ServiceProvider.GetRequiredService <SerializationManager>();

            var writer2 = new BinaryTokenStreamWriter();

            OrleansSerializer.Serialize(IntClass.Create(), writer2);
            OrleansInput  = writer2.ToBytes();
            OrleansBuffer = new BinaryTokenStreamReader(OrleansInput);
        }
예제 #10
0
        private T SerializerLoop <T>(T input)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var serializer = new ILBasedSerializer(new CachedTypeResolver());
#pragma warning restore CS0618 // Type or member is obsolete
            Assert.True(serializer.IsSupportedType(input.GetType()));

            var writer = new BinaryTokenStreamWriter();
            var serializationContext =
                new SerializationContext(this.fixture.SerializationManager)
            {
                StreamWriter = writer
            };
            serializer.Serialize(input, serializationContext, typeof(T));
            var deserializationContext = new DeserializationContext(this.fixture.SerializationManager)
            {
                StreamReader = new BinaryTokenStreamReader(writer.ToBytes())
            };

            return((T)serializer.Deserialize(typeof(T), deserializationContext));
        }
예제 #11
0
        private T SerializerLoop <T>(T input)
        {
            var serializer = new ILBasedSerializer(new CachedTypeResolver());

            Assert.True(serializer.IsSupportedType(input.GetType()));

            var writer = new BinaryTokenStreamWriter();
            var serializationContext =
                new SerializationContext(this.fixture.SerializationManager)
            {
                StreamWriter = writer
            };

            serializer.Serialize(input, serializationContext, typeof(T));
            var deserializationContext = new DeserializationContext(this.fixture.SerializationManager)
            {
                StreamReader = new BinaryTokenStreamReader(writer.ToBytes())
            };

            return((T)serializer.Deserialize(typeof(T), deserializationContext));
        }
예제 #12
0
        public List <ArraySegment <byte> > Serialize(SerializationManager serializationManager, out int headerLengthOut, out int bodyLengthOut)
        {
            var context = new SerializationContext(serializationManager)
            {
                StreamWriter = new BinaryTokenStreamWriter()
            };

            SerializationManager.SerializeMessageHeaders(Headers, context);

            if (bodyBytes == null)
            {
                var bodyStream = new BinaryTokenStreamWriter();
                serializationManager.Serialize(bodyObject, bodyStream);
                // We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
                // being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
                // serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
                // pretty high (an array allocation plus a bunch of copying).
                bodyBytes = bodyStream.ToBytes();
            }

            if (headerBytes != null)
            {
                BufferPool.GlobalPool.Release(headerBytes);
            }
            headerBytes = context.StreamWriter.ToBytes();
            int headerLength = context.StreamWriter.CurrentOffset;
            int bodyLength   = BufferLength(bodyBytes);

            var bytes = new List <ArraySegment <byte> >();

            bytes.Add(new ArraySegment <byte>(BitConverter.GetBytes(headerLength)));
            bytes.Add(new ArraySegment <byte>(BitConverter.GetBytes(bodyLength)));

            bytes.AddRange(headerBytes);
            bytes.AddRange(bodyBytes);

            headerLengthOut = headerLength;
            bodyLengthOut   = bodyLength;
            return(bytes);
        }
예제 #13
0
        static StructDeserializeBenchmark()
        {
            ProtoObj = new MemoryStream();
            ProtoBuf.Serializer.Serialize(ProtoObj, new IntStruct());

            HyperionObj = new MemoryStream();
            HyperionSerializer.Serialize(new IntStruct(), HyperionObj);

            // Hagar
            var services = new ServiceCollection()
                           .AddHagar()
                           .AddSerializers(typeof(Program).Assembly)
                           .BuildServiceProvider();

            HagarSerializer = services.GetRequiredService <Serializer <IntStruct> >();
            HagarData       = new SingleSegmentBuffer();
            var writer = new Writer(HagarData);

            Session = services.GetRequiredService <SessionPool>().GetSession();
            HagarSerializer.Serialize(new IntStruct(), Session, ref writer);

            // Orleans
            OrleansSerializer = new ClientBuilder()
                                .ConfigureDefaults()
                                .UseLocalhostClustering()
                                .Configure <ClusterOptions>(o => o.ClusterId = o.ServiceId = "test")
                                .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(SimpleClass).Assembly).WithCodeGeneration())
                                .Configure <SerializationProviderOptions>(options => options.FallbackSerializationProvider = typeof(SupportsNothingSerializer).GetTypeInfo())
                                .Build().ServiceProvider.GetRequiredService <SerializationManager>();

            var writer2 = new BinaryTokenStreamWriter();

            OrleansSerializer.Serialize(new IntStruct(), writer2);
            OrleansData   = writer2.ToBytes();
            OrleansBuffer = new BinaryTokenStreamReader(OrleansData);
        }
예제 #14
0
        //[Benchmark]
        public SimpleStruct OrleansStructRoundTrip()
        {
            var writer = new BinaryTokenStreamWriter();

            this.orleansSerializer.Serialize(this.structValue, writer);
            return((SimpleStruct)this.orleansSerializer.Deserialize(new BinaryTokenStreamReader(writer.ToBytes())));
        }