コード例 #1
0
ファイル: InsideRuntimeClient.cs プロジェクト: w-hb/orleans
 private void SafeSendResponse(Message message, object resultObject)
 {
     try
     {
         SendResponse(message, new Response(SerializationManager.DeepCopy(resultObject)));
     }
     catch (Exception exc)
     {
         logger.Warn(ErrorCode.IGC_SendResponseFailed,
                     "Exception trying to send a response: " + exc.Message, exc);
         SendResponse(message, Response.ExceptionResponse(exc));
     }
 }
コード例 #2
0
        SendResponseAsync(
            Message message,
            object resultObject)
        {
            if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
            {
                return(TaskDone.Done);
            }

            object deepCopy = null;

            try
            {
                // we're expected to notify the caller if the deep copy failed.
                deepCopy = SerializationManager.DeepCopy(resultObject);
            }
            catch (Exception exc2)
            {
                SendResponse(message, Response.ExceptionResponse(exc2));
                logger.Warn(
                    ErrorCode.ProxyClient_OGC_SendResponseFailed,
                    "Exception trying to send a response.", exc2);
                return(TaskDone.Done);
            }

            // the deep-copy succeeded.
            SendResponse(message, new Response(deepCopy));
            return(TaskDone.Done);
        }
コード例 #3
0
        /// <summary>
        /// Called from generated code.
        /// </summary>
        protected async Task <T> InvokeMethodAsync <T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
        {
            object[] argsDeepCopy = null;
            if (arguments != null)
            {
                CheckForGrainArguments(arguments);
                argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments);
            }

            var request = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy);

            if (IsUnordered)
            {
                options |= InvokeMethodOptions.Unordered;
            }

            Task <object> resultTask = InvokeMethod_Impl(request, null, options);

            if (resultTask == null)
            {
                return(default(T));
            }

            resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
            return((T)await resultTask);
        }
コード例 #4
0
        /// <summary>
        /// Called from generated code.
        /// </summary>
        protected Task <T> InvokeMethodAsync <T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
        {
            object[] argsDeepCopy = null;
            if (arguments != null)
            {
                CheckForGrainArguments(arguments);
                SetGrainCancellationTokensTarget(arguments, this);
                argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments);
            }

            var request = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy);

            if (IsUnordered)
            {
                options |= InvokeMethodOptions.Unordered;
            }

            Task <object> resultTask = InvokeMethod_Impl(request, null, options);

            if (resultTask == null)
            {
                if (typeof(T) == typeof(object))
                {
                    // optimize for most common case when using one way calls.
                    return(PublicOrleansTaskExtensions.CompletedTask as Task <T>);
                }

                return(Task.FromResult(default(T)));
            }

            resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
            return(resultTask.Unbox <T>());
        }
コード例 #5
0
        public async Task OnNextAsync(T item, StreamSequenceToken token)
        {
            if (token != null && !IsRewindable)
            {
                throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncBatchObserver.");
            }


            if (isDisposed)
            {
                throw new ObjectDisposedException(string.Format("{0}-{1}", GetType(), "OnNextAsync"));
            }

            if (!connectedToRendezvous)
            {
                if (!this.optimizeForImmutableData)
                {
                    // In order to avoid potential concurrency errors, synchronously copy the input before yielding the
                    // thread. DeliverItem below must also be take care to avoid yielding before copying for non-immutable objects.
                    item = (T)SerializationManager.DeepCopy(item);
                }

                await ConnectToRendezvous();
            }

            await myExtension.DeliverItem(stream.StreamId, item);
        }
コード例 #6
0
ファイル: RequestContext.cs プロジェクト: vansha/orleans
        public static Dictionary <string, object> Export(SerializationManager serializationManager)
        {
            var values = CallContextData.Value;

            if (PropagateActivityId)
            {
                var activityIdOverride = Trace.CorrelationManager.ActivityId;
                if (activityIdOverride != Guid.Empty)
                {
                    object existingActivityId;
                    if (values == null ||
                        !values.TryGetValue(E2_E_TRACING_ACTIVITY_ID_HEADER, out existingActivityId) ||
                        activityIdOverride != (Guid)existingActivityId)
                    {
                        // Create new copy before mutating data
                        values = values == null ? new Dictionary <string, object>() : new Dictionary <string, object>(values);
                        values[E2_E_TRACING_ACTIVITY_ID_HEADER] = activityIdOverride;
                    }
                }
            }

            return((values != null && values.Count > 0)
                ? (Dictionary <string, object>)serializationManager.DeepCopy(values)
                : null);
        }
コード例 #7
0
        public static Dictionary <string, object> Export(SerializationManager serializationManager)
        {
            Dictionary <string, object> values = GetContextData();

            if (PropagateActivityId)
            {
#if !NETSTANDARD
                var activityId = Trace.CorrelationManager.ActivityId;
#else
                var activityId = ActivityId.Value;
#endif
                if (activityId != Guid.Empty)
                {
                    values = values == null ? new Dictionary <string, object>() : new Dictionary <string, object>(values); // Create new copy before mutating data
                    values[E2_E_TRACING_ACTIVITY_ID_HEADER] = activityId;
                    // We have some changed data, so write RC data back into LogicalCallContext
                    SetContextData(values);
                }
            }
            if (values != null && values.Count != 0)
            {
                return((Dictionary <string, object>)serializationManager.DeepCopy(values));
            }
            return(null);
        }
コード例 #8
0
        public void ProtobuffSerializationTest_5_DeepCopy()
        {
            var input  = CreateAddressBook();
            var output = SerializationManager.DeepCopy(input);

            Assert.AreNotSame(input, output, "The serializer returned an instance of the same object");
            Assert.AreEqual(input, output, "The serialization didn't preserve the proper value");
        }
コード例 #9
0
        public void Serialization_ValueTypePhase1()
        {
            ValueTypeTestData data = new ValueTypeTestData(4);

            object obj = SerializationManager.DeepCopy(data);

            Assert.IsAssignableFrom <ValueTypeTestData>(obj);
            Assert.Equal <int>(4, ((ValueTypeTestData)obj).GetValue());
        }
コード例 #10
0
        public void SerializationTests_ThatCopyWasInvoked()
        {
            var data = new FakeSerialized {
                SomeData = "some data"
            };

            SerializationManager.DeepCopy(data);
            Assert.True(FakeSerializer.DeepCopyCalled);
        }
コード例 #11
0
        public void AzureQueueBatchContainerV2_DeepCopy_IfNotNullAndUsingExternalSerializer()
        {
            var container = CreateAzureQueueBatchContainer();
            var copy      = AzureQueueBatchContainerV2.DeepCopy(container) as AzureQueueBatchContainerV2;

            ValidateIdenticalQueueBatchContainerButNotSame(container, copy);
            copy = SerializationManager.DeepCopy(container) as AzureQueueBatchContainerV2;
            ValidateIdenticalQueueBatchContainerButNotSame(container, copy);
        }
コード例 #12
0
        public void Serialization_ValueTypePhase1()
        {
            ValueTypeTestData data = new ValueTypeTestData(4);

            object obj = SerializationManager.DeepCopy(data);

            Assert.IsInstanceOfType(obj, typeof(ValueTypeTestData), "Deserialized result is of wrong type");
            Assert.AreEqual <int>(4, ((ValueTypeTestData)obj).GetValue(), "Deserialized result is incorrect");
        }
コード例 #13
0
        internal static object OrleansSerializationLoop(object input, bool includeWire = true)
        {
            var copy = SerializationManager.DeepCopy(input);

            if (includeWire)
            {
                copy = SerializationManager.RoundTripSerializationForTesting(copy);
            }
            return(copy);
        }
コード例 #14
0
        public void SimpleBondSchemaCopyTest()
        {
            var schema = new SimpleBondSchema {
                SomeValue = int.MaxValue
            };
            var output = SerializationManager.DeepCopy(schema) as SimpleBondSchema;

            Assert.AreNotSame(output, schema, "The serializer returned an instance of the same object");
            Assert.AreEqual(schema.SomeValue, output.SomeValue, "The serialization didn't preserve the proper value");
        }
コード例 #15
0
        public void SimpleGenericBondSchemaCopyTest()
        {
            var schema = new SimpleGenericSchema <int> {
                SomeValue = int.MaxValue
            };
            var output = SerializationManager.DeepCopy(schema) as SimpleGenericSchema <int>;

            Assert.NotSame(output, schema);                   //The serializer returned an instance of the same object
            Assert.Equal(schema.SomeValue, output.SomeValue); //The serialization didn't preserve the proper value
        }
コード例 #16
0
        public void Serialize_CustomCopier()
        {
            var original = new ClassWithCustomCopier()
            {
                IntProperty = 5, StringProperty = "Hello"
            };
            var copy = SerializationManager.DeepCopy(original);

            Assert.Equal(1, ClassWithCustomCopier.CopyCounter); //Custom copier was not called
        }
コード例 #17
0
 public virtual Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
 {
     Log.Info(0, "ReadStateAsync for {0} {1}", grainType, grainReference);
     Interlocked.Increment(ref readCount);
     lock (StateStore)
     {
         var storedState = GetLastState(grainType, grainReference, grainState);
         grainState.State = SerializationManager.DeepCopy(storedState); // Read current state data
     }
     return(TaskDone.Done);
 }
コード例 #18
0
 internal void SetApplicationHeaders(Dictionary <string, object> data)
 {
     lock (headers)
     {
         foreach (var item in data)
         {
             string key = Header.APPLICATION_HEADER_FLAG + item.Key;
             headers[key] = SerializationManager.DeepCopy(item.Value);
         }
     }
 }
コード例 #19
0
        public void OrleansSerialization_HttpRequestException_IsEquivalent()
        {
            var expected = new HttpRequestException("HTTP request exception").ThrowAndCatch();

            var actual1 = (HttpRequestException)_serializationManager.DeepCopy(expected);

            AssertExceptionsAreEqual(expected, actual1);

            var actual  = _serializationManager.RoundTripSerializationForTesting(expected);
            var actual2 = _serializationManager.DeserializeFromByteArray <HttpRequestException>(_serializationManager.SerializeToByteArray(expected));

            AssertExceptionsAreEqual(expected, actual2);
            AssertExceptionsAreEqual(expected, actual);
        }
コード例 #20
0
 public void DeepCopyTests_ImmutableCollections()
 {
     {
         var original = ImmutableDictionary.CreateBuilder <string, Dictionary <string, string> >();
         original.Add("a", new Dictionary <string, string>()
         {
             { "0", "1" },
             { "1", "2" }
         });
         var dict = original.ToImmutable();
         var copy = (ImmutableDictionary <string, Dictionary <string, string> >)SerializationManager.DeepCopy(dict);
         Assert.Same(dict, copy);
     }
     {
         var original = ImmutableArray.Create <string>("1", "2", "3");
         var copy     = (ImmutableArray <string>)SerializationManager.DeepCopy(original);
         Assert.Equal(original, copy);
     }
     {
         var original = ImmutableHashSet.Create("1", "2", "3");
         var copy     = (ImmutableHashSet <string>)SerializationManager.DeepCopy(original);
         Assert.Same(original, copy);
     }
     {
         var original = ImmutableList.Create("1", "2", "3");
         var copy     = (ImmutableList <string>)SerializationManager.DeepCopy(original);
         Assert.Same(original, copy);
     }
     {
         var original = ImmutableQueue.Create("1", "2", "3");
         var copy     = (ImmutableQueue <string>)SerializationManager.DeepCopy(original);
         Assert.Same(original, copy);
     }
     {
         var original = ImmutableSortedDictionary.CreateBuilder <string, Dictionary <string, string> >();
         original.Add("a", new Dictionary <string, string>()
         {
             { "0", "1" },
             { "1", "2" }
         });
         var dict = original.ToImmutable();
         var copy = (ImmutableSortedDictionary <string, Dictionary <string, string> >)SerializationManager.DeepCopy(dict);
         Assert.Same(dict, copy);
     }
     {
         var original = ImmutableSortedSet.Create("1", "2", "3");
         var copy     = (ImmutableSortedSet <string>)SerializationManager.DeepCopy(original);
         Assert.Same(original, copy);
     }
 }
コード例 #21
0
        private void RunGrainReferenceSerializationTest <TGrainInterface>()
        {
            var counters = new List <CounterStatistic>
            {
                CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_SERIALIZATION),
                CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_DESERIALIZATION),
                CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_DEEPCOPIES)
            };

            // Get the (generated) grain reference implementation for a particular grain interface type.
            var grainReference = this.GetGrainReference <TGrainInterface>();

            // Get the current value of each of the fallback serialization counters.
            var initial = counters.Select(_ => _.GetCurrentValue()).ToList();

            // Serialize and deserialize the grain reference.
            var writer = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(grainReference, writer);
            var deserialized = SerializationManager.Deserialize(new BinaryTokenStreamReader(writer.ToByteArray()));
            var copy         = (GrainReference)SerializationManager.DeepCopy(deserialized);

            // Get the final value of the fallback serialization counters.
            var final = counters.Select(_ => _.GetCurrentValue()).ToList();

            // Ensure that serialization was correctly performed.
            Assert.IsInstanceOfType(
                deserialized,
                grainReference.GetType(),
                "Deserialized GrainReference type should match original type");
            var deserializedGrainReference = (GrainReference)deserialized;

            Assert.IsTrue(
                deserializedGrainReference.GrainId.Equals(grainReference.GrainId),
                "Deserialized GrainReference should have same GrainId as original value.");
            Assert.IsInstanceOfType(copy, grainReference.GetType(), "DeepCopy GrainReference type should match original type");
            Assert.IsTrue(
                copy.GrainId.Equals(grainReference.GrainId),
                "DeepCopy GrainReference should have same GrainId as original value.");

            // Check that the counters have not changed.
            var initialString = string.Join(",", initial);
            var finalString   = string.Join(",", final);

            Assert.AreEqual(initialString, finalString, "GrainReference serialization should not use fallback serializer.");
        }
コード例 #22
0
        public virtual Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            Log.Info(0, "WriteStateAsync for {0} {1}", grainType, grainReference);
            Interlocked.Increment(ref writeCount);
            lock (StateStore)
            {
                var storedState = SerializationManager.DeepCopy(grainState.State); // Store current state data
                var stateStore  = new Dictionary <string, object> {
                    { stateStoreKey, storedState }
                };
                StateStore.WriteRow(MakeGrainStateKeys(grainType, grainReference), stateStore, grainState.ETag);

                LastId    = GetId(grainReference);
                LastState = storedState;
            }
            return(TaskDone.Done);
        }
コード例 #23
0
        private void CalculateTentativeState()
        {
            // copy the master
            this.tentativeStateInternal = (TLogView)SerializationManager.DeepCopy(LastConfirmedView());

            // Now apply all operations in pending
            foreach (var u in this.pending)
            {
                try
                {
                    Host.UpdateView(this.tentativeStateInternal, u.Entry);
                }
                catch (Exception e)
                {
                    Services.CaughtUserCodeException("UpdateView", nameof(CalculateTentativeState), e);
                }
            }
        }
コード例 #24
0
        private void ReportException(Message message, Exception exception)
        {
            var request = (InvokeMethodRequest)message.BodyObject;

            switch (message.Direction)
            {
            default:
                throw new InvalidOperationException();

            case Message.Directions.OneWay:
            {
                logger.Error(
                    ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke,
                    String.Format(
                        "Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.",
                        request.MethodId,
                        request.InterfaceId),
                    exception);
                break;
            }

            case Message.Directions.Request:
            {
                Exception deepCopy = null;
                try
                {
                    // we're expected to notify the caller if the deep copy failed.
                    deepCopy = (Exception)SerializationManager.DeepCopy(exception);
                }
                catch (Exception ex2)
                {
                    SendResponse(message, Response.ExceptionResponse(ex2));
                    logger.Warn(
                        ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
                        "Exception trying to send an exception response", ex2);
                    return;
                }
                // the deep-copy succeeded.
                var response = Response.ExceptionResponse(deepCopy);
                SendResponse(message, response);
                break;
            }
            }
        }
コード例 #25
0
        public void ID_IsSystem()
        {
            GrainId testGrain = Constants.DirectoryServiceId;

            output.WriteLine("Testing GrainID " + testGrain);
            Assert.True(testGrain.IsSystemTarget); // System grain ID is not flagged as a system ID

            GrainId sGrain = (GrainId)SerializationManager.DeepCopy(testGrain);

            output.WriteLine("Testing GrainID " + sGrain);
            Assert.True(sGrain.IsSystemTarget); // String round-trip grain ID is not flagged as a system ID
            Assert.Equal(testGrain, sGrain);    // Should be equivalent GrainId object
            Assert.Same(testGrain, sGrain);     // Should be same / intern'ed GrainId object

            ActivationId testActivation = ActivationId.GetSystemActivation(testGrain, SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 2456), 0));

            output.WriteLine("Testing ActivationID " + testActivation);
            Assert.True(testActivation.IsSystem); // System activation ID is not flagged as a system ID
        }
コード例 #26
0
ファイル: RequestContext.cs プロジェクト: supwar/orleans
        internal static void ExportToMessage(Message msg)
        {
            Dictionary <string, object> values = GetContextData();

            if (PropagateActivityId)
            {
                Guid activityId = Trace.CorrelationManager.ActivityId;
                if (activityId != Guid.Empty)
                {
                    values = values == null ? new Dictionary <string, object>() : new Dictionary <string, object>(values); // Create new copy before mutating data
                    values[E2_E_TRACING_ACTIVITY_ID_HEADER] = activityId;
                    // We have some changed data, so write RC data back into LogicalCallContext
                    SetContextData(values);
                }
            }
            if (values != null && values.Count != 0)
            {
                msg.RequestContextData = values.ToDictionary(kvp => kvp.Key, kvp => SerializationManager.DeepCopy(kvp.Value));
            }
        }
コード例 #27
0
        public async Task <int> DoRead(bool recover)
        {
            var original = SerializationManager.DeepCopy(State);

            try
            {
                await ReadStateAsync();
            }
            catch (Exception exc)
            {
                if (!recover)
                {
                    throw;
                }

                GetLogger().Warn(0, "Grain is handling error in DoRead - Resetting value to " + original, exc);
                State = (PersistenceTestGrainState)original;
            }
            return(State.Field1);
        }
コード例 #28
0
        public async Task DoWrite(int val, bool recover)
        {
            var original = SerializationManager.DeepCopy(State);

            try
            {
                State.Field1 = val;
                await WriteStateAsync();
            }
            catch (Exception exc)
            {
                if (!recover)
                {
                    throw;
                }

                GetLogger().Warn(0, "Grain is handling error in DoWrite - Resetting value to " + original, exc);
                State = (PersistenceTestGrainState)original;
            }
        }
コード例 #29
0
        public void Serialization_LargeTestData()
        {
            var data = new LargeTestData
            {
                Description =
                    "This is a test. This is only a test. In the event of a real execution, this would contain actual data.",
                EnumValue = TestEnum.First
            };

            data.SetBit(13);
            data.SetEnemy(17, CampaignEnemyTestType.Enemy1);

            object obj = SerializationManager.DeepCopy(data);

            Assert.IsAssignableFrom <LargeTestData>(obj);

            object copy = SerializationManager.RoundTripSerializationForTesting(obj);

            Assert.IsAssignableFrom <LargeTestData>(copy);
        }
コード例 #30
0
        public void Serialization_LargeTestData()
        {
            var data = new LargeTestData
            {
                Description =
                    "This is a test. This is only a test. In the event of a real execution, this would contain actual data.",
                EnumValue = TestEnum.First
            };

            data.SetBit(13);
            data.SetEnemy(17, CampaignEnemyTestType.Enemy1);

            object obj = SerializationManager.DeepCopy(data);

            Assert.IsInstanceOfType(obj, typeof(LargeTestData), "Copied result is of wrong type");

            object copy = SerializationManager.RoundTripSerializationForTesting(obj);

            Assert.IsInstanceOfType(copy, typeof(LargeTestData), "Deserialized result is of wrong type");
        }