예제 #1
0
            private void PositiveTest(int responseCode, int?expectedSenderCapacity, int?expectedBufferCapacity, int?expectedStorageCapacity)
            {
                const int RetryAfterSeconds          = 2;
                string    retryAfter                 = DateTime.Now.ToUniversalTime().AddSeconds(RetryAfterSeconds).ToString("R", CultureInfo.InvariantCulture);
                const int WaitForTheFirstApplyAsync  = 100;
                int       waitForTheSecondApplyAsync = (RetryAfterSeconds * 1000) /*to milliseconds*/ +
                                                       500 /**magic number to wait for other code before/after
                                                            * timer which calls 2nd ApplyAsync
                                                            **/;

                var policyApplied = new AutoResetEvent(false);
                var transmitter   = new StubTransmitter();

                transmitter.OnApplyPolicies = () =>
                {
                    policyApplied.Set();
                };

                var policy = new ThrottlingTransmissionPolicy();

                policy.Initialize(transmitter);

                transmitter.OnTransmissionSent(
                    new TransmissionProcessedEventArgs(
                        new StubTransmission(), null, new HttpWebResponseWrapper()
                {
                    StatusCode       = responseCode,
                    RetryAfterHeader = retryAfter
                }));

                Assert.IsTrue(policyApplied.WaitOne(WaitForTheFirstApplyAsync));

                Assert.AreEqual(expectedSenderCapacity, policy.MaxSenderCapacity);
                Assert.AreEqual(expectedBufferCapacity, policy.MaxBufferCapacity);
                Assert.AreEqual(expectedStorageCapacity, policy.MaxStorageCapacity);

                Assert.IsTrue(policyApplied.WaitOne(waitForTheSecondApplyAsync));

                // Check that it resets after retry-after interval
                Assert.IsNull(policy.MaxSenderCapacity);
                Assert.IsNull(policy.MaxBufferCapacity);
                Assert.IsNull(policy.MaxStorageCapacity);
            }
예제 #2
0
            public void StopsTransmissionSendingWhenTransmissionTimesOut()
            {
                var policyApplied = new AutoResetEvent(false);
                var transmitter   = new StubTransmitter(new TestableBackoffLogicManager(TimeSpan.FromSeconds(10)));

                transmitter.OnApplyPolicies = () =>
                {
                    policyApplied.Set();
                };

                var policy = new ErrorHandlingTransmissionPolicy();

                policy.Initialize(transmitter);

                transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(new StubTransmission(), CreateException(statusCode: 408)));

                Assert.IsTrue(policyApplied.WaitOne(100));
                Assert.AreEqual(0, policy.MaxSenderCapacity);
            }
예제 #3
0
            public void RetriesFailedTransmissionIfItsNumberOfAttemptsDidNotReachMaximum()
            {
                Transmission enqueuedTransmission = null;
                var          transmitter          = new StubTransmitter();

                transmitter.OnEnqueue = transmission =>
                {
                    enqueuedTransmission = transmission;
                };

                var policy = new ErrorHandlingTransmissionPolicy();

                policy.Initialize(transmitter);

                var failedTransmission = new StubTransmission();

                transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(failedTransmission, CreateException(statusCode: 408)));

                Assert.AreSame(failedTransmission, enqueuedTransmission);
            }
예제 #4
0
            public void ResumesTransmissionSenderAfterPauseDuration()
            {
                var policyApplied = new AutoResetEvent(false);
                var transmitter   = new StubTransmitter(new TestableBackoffLogicManager(TimeSpan.FromMilliseconds(1)));

                transmitter.OnApplyPolicies = () =>
                {
                    policyApplied.Set();
                };

                var policy = new ErrorHandlingTransmissionPolicy();

                policy.Initialize(transmitter);

                transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(new StubTransmission(), CreateException(statusCode: 408)));

                Assert.True(policyApplied.WaitOne(100));
                Assert.True(policyApplied.WaitOne(100));
                Assert.Null(policy.MaxSenderCapacity);
            }
예제 #5
0
        public void NewTransmissionCreatedByIndexesFromResponse()
        {
            IList <Transmission> enqueuedTransmissions = new List <Transmission>();
            var transmitter = new StubTransmitter
            {
                OnEnqueue = t => { enqueuedTransmissions.Add(t); }
            };

            var policy = new PartialSuccessTransmissionPolicy();

            policy.Initialize(transmitter);

            var items = new List <ITelemetry>
            {
                new EventTelemetry("1"),
                new EventTelemetry("2"),
                new EventTelemetry("3"),
            };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding");

            string response = BackendResponseHelper.CreateBackendResponse(
                itemsReceived: 3,
                itemsAccepted: 1,
                errorCodes: new[] { "439", "439" });

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content    = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            string[] newItems = JsonSerializer
                                .Deserialize(enqueuedTransmissions[0].Content)
                                .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            Assert.AreEqual(2, newItems.Length);
            Assert.IsTrue(newItems[0].Contains("\"name\":\"1\""));
            Assert.IsTrue(newItems[1].Contains("\"name\":\"2\""));
        }
예제 #6
0
            public void DoesNotRetrySuccessfulTransmission()
            {
                Transmission enqueuedTransmission = null;
                var          transmitter          = new StubTransmitter();

                transmitter.OnEnqueue = transmission =>
                {
                    enqueuedTransmission = transmission;
                };

                var policy = new ErrorHandlingTransmissionPolicy();

                policy.Initialize(transmitter);

                var successfulTransmission = new StubTransmission();

                transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(successfulTransmission));

                Assert.IsNull(enqueuedTransmission);
                Assert.AreEqual(0, transmitter.BackoffLogicManager.ConsecutiveErrors);
            }
예제 #7
0
            private void ResumesTransmissionSenderAfterPauseDuration(int responseStatusCode)
            {
                var policyApplied = new AutoResetEvent(false);
                var transmitter   = new StubTransmitter(new TestableBackoffLogicManager(TimeSpan.FromMilliseconds(1)));

                transmitter.OnApplyPolicies = () => { policyApplied.Set(); };

                var policy = new ErrorHandlingTransmissionPolicy();

                policy.Initialize(transmitter);

                transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(new StubTransmission(),
                                                                                  new Exception("Error"),
                                                                                  new HttpWebResponseWrapper()
                {
                    StatusCode = responseStatusCode
                }));

                Assert.IsTrue(policyApplied.WaitOne(100));
                Assert.IsTrue(policyApplied.WaitOne(100));
                Assert.IsNull(policy.MaxSenderCapacity);
            }
            public void AssertUnsupportedResponseCodeDoesntChangeCapacity()
            {
                var transmitter = new StubTransmitter();

                transmitter.OnApplyPolicies = () =>
                {
                    throw new Exception("Apply shouldn't be called because unsupported response code was passed");
                };

                var policy = new ThrottlingTransmissionPolicy();

                policy.Initialize(transmitter);

                transmitter.OnTransmissionSent(
                    new TransmissionProcessedEventArgs(
                        new StubTransmission(),
                        CreateThrottledResponse(ResponseCodeUnsupported, 1)));

                Assert.Null(policy.MaxSenderCapacity);
                Assert.Null(policy.MaxBufferCapacity);
                Assert.Null(policy.MaxStorageCapacity);
            }
예제 #9
0
            public void RetriesFailedTransmissionIfItsNumberOfAttemptsDidNotReachMaximum()
            {
                Transmission enqueuedTransmission = null;
                var          transmitter          = new StubTransmitter();

                transmitter.OnEnqueue = transmission =>
                {
                    enqueuedTransmission = transmission;
                };

                var policy = new ErrorHandlingTransmissionPolicy();

                policy.Initialize(transmitter);

                var failedTransmission = new StubTransmission();

                transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(failedTransmission, new Exception("Error"), new HttpWebResponseWrapper()
                {
                    StatusCode = ResponseStatusCodes.InternalServerError
                }));

                Assert.AreSame(failedTransmission, enqueuedTransmission);
            }
            public void CannotParseRetryAfterWritesToEventSource()
            {
                const string UnparsableDate = "no one can parse me! :)";

                var transmitter = new StubTransmitter();
                var policy      = new ThrottlingTransmissionPolicy();

                policy.Initialize(transmitter);

                using (var listener = new TestEventListener())
                {
                    const long AllKeyword = -1;
                    listener.EnableEvents(TelemetryChannelEventSource.Log, EventLevel.LogAlways, (EventKeywords)AllKeyword);

                    transmitter.OnTransmissionSent(
                        new TransmissionProcessedEventArgs(
                            new StubTransmission(),
                            CreateThrottledResponse(ResponseCodeTooManyRequests, UnparsableDate)));

                    EventWrittenEventArgs trace = listener.Messages.First(args => args.EventId == 24);
                    Assert.Equal(UnparsableDate, (string)trace.Payload[0]);
                }
            }
            public void AssertPaymentRequiredDoesntChangeCapacity()
            {
                var transmitter = new StubTransmitter();

                transmitter.OnApplyPolicies = () =>
                {
                    throw new Exception("Apply shouldn't be called because unsupported response code was passed");
                };

                var policy = new ThrottlingTransmissionPolicy();

                policy.Initialize(transmitter);

                transmitter.OnTransmissionSent(
                    new TransmissionProcessedEventArgs(
                        new StubTransmission(), null, new HttpWebResponseWrapper()
                {
                    StatusCode = ResponseCodePaymentRequired
                }));

                Assert.IsNull(policy.MaxSenderCapacity);
                Assert.IsNull(policy.MaxBufferCapacity);
                Assert.IsNull(policy.MaxStorageCapacity);
            }
            public void AssertIfDateParseErrorCausesDefaultDelay()
            {
                var policyApplied = new AutoResetEvent(false);
                var transmitter   = new StubTransmitter();

                transmitter.OnApplyPolicies = () =>
                {
                    policyApplied.Set();
                };

                var policy = new ThrottlingTransmissionPolicy();

                policy.Initialize(transmitter);

                transmitter.OnTransmissionSent(
                    new TransmissionProcessedEventArgs(
                        new StubTransmission(),
                        CreateThrottledResponse(ResponseCodeTooManyRequests, "no one can parse me! :)")));

                Assert.True(policyApplied.WaitOne(100));
                Assert.Null(policy.MaxSenderCapacity);
                Assert.Null(policy.MaxBufferCapacity);
                Assert.Null(policy.MaxStorageCapacity);
            }
예제 #13
0
        public void ItemsAreEnqueuedOnFlushAsync()
        {
            IList <Transmission> enqueuedTransmissions = new List <Transmission>();
            var transmitter = new StubTransmitter
            {
                OnEnqueue = t => { enqueuedTransmissions.Add(t); }
            };

            var policy = new PartialSuccessTransmissionPolicy();

            policy.Initialize(transmitter);

            var items = new List <ITelemetry> {
                new EventTelemetry(), new EventTelemetry()
            };
            Transmission transmission = new Transmission(new Uri("http://uri"), items, "type", "encoding")
            {
                IsFlushAsyncInProgress = true
            };

            string response = BackendResponseHelper.CreateBackendResponse(
                itemsReceived: 2,
                itemsAccepted: 1,
                errorCodes: new[] { "429" });

            var wrapper = new HttpWebResponseWrapper
            {
                StatusCode = 206,
                Content    = response
            };

            transmitter.OnTransmissionSent(new TransmissionProcessedEventArgs(transmission, null, wrapper));

            Assert.AreEqual(1, enqueuedTransmissions.Count);
            Assert.IsTrue(transmission.IsFlushAsyncInProgress);
        }