public async Task When_server_returns_HTTP_error_a_reconnect_attempt_is_made()
        {
            var messageData = "hello";

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.WithStatus(HttpStatusCode.Unauthorized));
            handler.QueueResponse(StubResponse.StartStream(
                                      StreamAction.Write("event: put\ndata: " + messageData + "\n\n")));

            var evt = new EventSource(new Configuration(_uri, handler));

            var errorReceiver = new ErrorReceiver();

            evt.Error += errorReceiver;

            var messageReceiver = new MessageReceiver();

            evt.MessageReceived += messageReceiver;
            evt.MessageReceived += (_, e) => evt.Close();

            await evt.StartAsync();

            Assert.Equal(2, handler.GetRequests().Count());
            Assert.NotNull(errorReceiver.ErrorReceived);
            var ex = Assert.IsType <EventSourceServiceUnsuccessfulResponseException>(errorReceiver.ErrorReceived);

            Assert.Equal((int)HttpStatusCode.Unauthorized, ex.StatusCode);
            Assert.Equal(messageData, messageReceiver.RequireSingleEvent().Message.Data);
        }
Beispiel #2
0
        public void NonUtf8EncodingIsReadAsStrings(bool preferUtf8Data)
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(
                                      Encoding.GetEncoding("iso-8859-1"),
                                      BasicStreamTestParams.StreamActions));

            var config = Configuration.Builder(_uri).HttpMessageHandler(handler)
                         .LogAdapter(_testLogging)
                         .PreferDataAsUtf8Bytes(preferUtf8Data)
                         .Build();

            using (var es = new EventSource(config))
            {
                var sink = new EventSink(es, _testLogging)
                {
                    ExpectUtf8Data = false
                };

                _ = Task.Run(es.StartAsync);

                sink.ExpectActions(BasicStreamTestParams.ExpectedEventActions);
            }
        }
        public async Task When_response_exceeds_read_timeout_then_read_timeout_exception_occurs()
        {
            TimeSpan readTimeout = TimeSpan.FromSeconds(4);
            TimeSpan timeToWait  = readTimeout.Add(TimeSpan.FromSeconds(1));

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(
                                      StreamAction.Write(":\n\n").AfterDelay(timeToWait)));
            handler.QueueResponse(StubResponse.StartStream());

            var config = new ConfigurationBuilder(_uri).MessageHandler(handler).ReadTimeout(readTimeout).Build();
            var evt    = new EventSource(config);

            var receiver = new ErrorReceiver();

            evt.Error += receiver;
            evt.Error += (_, e) => evt.Close();

            await evt.StartAsync();

            Assert.NotNull(receiver.ErrorReceived);
            Assert.Contains(receiver.ErrorReceived.Message, Resources.EventSourceService_Read_Timeout);
            Assert.Equal(ReadyState.Closed, receiver.SourceStateReceived);
            Assert.Equal(ReadyState.Shutdown, evt.ReadyState);
        }
        public async Task Given_content_type_not_equal_to_eventstream_when_the_http_response_is_received_then_error_event_should_occur()
        {
            var handler = new StubMessageHandler();

            var response =
                new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("testing", System.Text.Encoding.UTF8)
            };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");

            handler.QueueResponse(StubResponse.WithResponse(response));

            var config = new Configuration(_uri, handler);

            var evt      = new EventSource(config);
            var receiver = new ErrorReceiver();

            evt.Error += receiver;
            evt.Error += (_, e) => evt.Close();

            await evt.StartAsync();

            Assert.NotNull(receiver.ErrorReceived);
            Assert.Equal(ReadyState.Closed, receiver.SourceStateReceived);
            Assert.Equal(ReadyState.Shutdown, evt.ReadyState);
        }
        public async Task Given_bad_http_responses_then_retry_delay_durations_should_increase()
        {
            var handler = new StubMessageHandler();

            var nAttempts = 2;

            for (int i = 0; i < nAttempts; i++)
            {
                handler.QueueResponse(StubResponse.WithIOError());
            }
            handler.QueueResponse(StubResponse.StartStream());

            var evt = new EventSource(new Configuration(_uri, handler));

            var backoffs = new List <TimeSpan>();

            evt.Error += (_, e) =>
            {
                backoffs.Add(evt.BackOffDelay);
                if (backoffs.Count >= nAttempts)
                {
                    evt.Close();
                }
            };

            await evt.StartAsync();

            Assert.NotEmpty(backoffs);
            Assert.NotEqual(backoffs[0], backoffs[1]);
            Assert.True(backoffs[1] > backoffs[0]);
        }
        public async Task When_reconnecting_the_outgoing_request_contains_Last_Event_Id_header()
        {
            var lastEventId    = "10";
            var firstResponse  = $"id:{lastEventId}\nevent: put\ndata: this is a test message\n\n";
            var secondResponse = $"id:20\nevent: put\ndata: this is a test message\n\n";

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(firstResponse), StreamAction.CloseStream()));
            handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(secondResponse), StreamAction.CloseStream()));

            var evt   = new EventSource(new Configuration(_uri, handler));
            var first = true;

            handler.RequestReceived += (s, r) =>
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    evt.Close();
                }
            };

            await evt.StartAsync();

            var requests = handler.GetRequests().ToList();

            Assert.False(requests[0].Headers.Contains(Constants.LastEventIdHttpHeader));
            Assert.True(requests[1].Headers.Contains(Constants.LastEventIdHttpHeader));
            Assert.True(requests[1].Headers.GetValues(Constants.LastEventIdHttpHeader).Contains(lastEventId));
        }
        public void DetectReadTimeout()
        {
            TimeSpan readTimeout = TimeSpan.FromMilliseconds(300);
            TimeSpan timeToWait  = readTimeout + readTimeout;

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(
                                      StreamAction.Write(":comment1\n"),
                                      StreamAction.Write(":comment2\n"),
                                      StreamAction.Write(":comment3\n").AfterDelay(timeToWait))
                                  );
            handler.QueueResponse(StubResponse.StartStream());

            using (var es = StartEventSource(handler, out var eventSink, config => config.ReadTimeout(readTimeout)))
            {
                eventSink.ExpectActions(
                    EventSink.OpenedAction(),
                    EventSink.CommentReceivedAction(":comment1"),
                    EventSink.CommentReceivedAction(":comment2"),
                    EventSink.ErrorAction(new ReadTimeoutException()),
                    EventSink.ClosedAction()
                    );
            }
        }
        public void ReconnectAfterHttpError()
        {
            HttpStatusCode error1 = HttpStatusCode.BadRequest, error2 = HttpStatusCode.InternalServerError;
            var            message = new MessageEvent("put", "hello", _uri);

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.WithStatus(error1));
            handler.QueueResponse(StubResponse.WithStatus(error2));
            handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(message)));

            using (var es = MakeEventSource(handler, builder => builder.InitialRetryDelay(TimeSpan.FromMilliseconds(20))))
            {
                var eventSink = new EventSink(es, _testLogging);
                _ = Task.Run(es.StartAsync);

                var action1 = eventSink.ExpectAction();
                var ex1     = Assert.IsType <EventSourceServiceUnsuccessfulResponseException>(action1.Exception);
                Assert.Equal((int)error1, ex1.StatusCode);

                eventSink.ExpectActions(EventSink.ClosedAction());

                var action2 = eventSink.ExpectAction();
                var ex2     = Assert.IsType <EventSourceServiceUnsuccessfulResponseException>(action2.Exception);
                Assert.Equal((int)error2, ex2.StatusCode);

                eventSink.ExpectActions(
                    EventSink.ClosedAction(),
                    EventSink.OpenedAction(),
                    EventSink.MessageReceivedAction(message)
                    );
            }
        }
        public void RetryDelayDurationsShouldIncrease()
        {
            var handler = new StubMessageHandler();

            var nAttempts = 3;

            for (var i = 0; i < nAttempts; i++)
            {
                handler.QueueResponse(StubResponse.StartStream(
                                          StreamAction.Write(":hi\n"),
                                          StreamAction.CloseStream()));
            }
            handler.QueueResponse(StubResponse.StartStream());

            var backoffs = new List <TimeSpan>();

            using (var es = MakeEventSource(handler, builder => builder.InitialRetryDelay(TimeSpan.FromMilliseconds(100))))
            {
                _          = new EventSink(es, _testLogging);
                es.Closed += (_, state) =>
                {
                    backoffs.Add(es.BackOffDelay);
                };

                _ = Task.Run(es.StartAsync);

                for (int i = 0; i <= nAttempts; i++)
                {
                    _ = handler.AwaitRequest();
                }
            }

            AssertBackoffsAlwaysIncrease(backoffs, nAttempts);
        }
Beispiel #10
0
        public void CanReceiveUtf8EventDataAsBytes(bool setExplicitEncoding)
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(
                                      setExplicitEncoding ? Encoding.UTF8 : null,
                                      BasicStreamTestParams.StreamActions));

            var config = Configuration.Builder(_uri).HttpMessageHandler(handler)
                         .LogAdapter(_testLogging)
                         .PreferDataAsUtf8Bytes(true)
                         .Build();

            using (var es = new EventSource(config))
            {
                var eventSink = new EventSink(es, _testLogging)
                {
                    ExpectUtf8Data = true
                };

                _ = Task.Run(es.StartAsync);

                eventSink.ExpectActions(BasicStreamTestParams.ExpectedEventActions);
            }
        }
        public async Task When_Configuration_Request_headers_are_set_then_the_outgoing_request_contains_those_same_headers()
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream());

            var headers = new Dictionary <string, string> {
                { "User-Agent", "mozilla" }, { "Authorization", "testing" }
            };

            var config = new ConfigurationBuilder(_uri).MessageHandler(handler)
                         .RequestHeaders(headers).Build();

            var evt = new EventSource(config);

            handler.RequestReceived += (s, r) => evt.Close();

            await evt.StartAsync();

            var request = handler.GetRequests().First();

            Assert.True(headers.All(
                            item =>
                            request.Headers.Contains(item.Key) &&
                            request.Headers.GetValues(item.Key).Contains(item.Value)
                            ));
        }
        public void CustomMethod()
        {
            var handler = new StubMessageHandler(StubResponse.StartStream());

            using (var es = MakeEventSource(handler, builder => builder.Method(HttpMethod.Post)))
            {
                _ = Task.Run(es.StartAsync);

                var req = handler.AwaitRequest();
                Assert.Equal(HttpMethod.Post, req.Method);
            }
        }
        public async Task CustomHttpClientIsNotClosedWhenEventSourceCloses()
        {
            var handler = new StubMessageHandler(StubResponse.WithStatus(HttpStatusCode.OK));

            using (var client = new HttpClient(handler))
            {
                var es = new EventSource(Configuration.Builder(_uri).HttpClient(client).Build());
                es.Close();

                await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, _uri));
            }
        }
        public void LastEventIdHeaderIsNotSetByDefault()
        {
            var handler = new StubMessageHandler(StubResponse.StartStream());

            using (var es = MakeEventSource(handler))
            {
                _ = Task.Run(es.StartAsync);

                var req = handler.AwaitRequest();
                Assert.False(req.Headers.Contains(Constants.LastEventIdHttpHeader));
            }
        }
        public void CanRestartStream(bool resetBackoff)
        {
            // This test is in EventSourceStreamReadingTest rather than EventSourceReconnectingTest
            // because the important thing here is that the stream reading logic can be interrupted.
            int nAttempts    = 3;
            var initialDelay = TimeSpan.FromMilliseconds(50);

            var anEvent = new MessageEvent("put", "x", _uri);
            var stream  = StubResponse.StartStream(StreamAction.Write(anEvent));
            var handler = new StubMessageHandler();

            for (var i = 0; i <= nAttempts; i++)
            {
                handler.QueueResponse(stream);
            }

            var backoffs = new List <TimeSpan>();

            using (var es = MakeEventSource(handler, builder => builder.InitialRetryDelay(initialDelay)))
            {
                var sink = new EventSink(es, _testLogging);
                es.Closed += (_, ex) =>
                {
                    backoffs.Add(es.BackOffDelay);
                };
                _ = Task.Run(es.StartAsync);

                sink.ExpectActions(
                    EventSink.OpenedAction(),
                    EventSink.MessageReceivedAction(anEvent)
                    );

                for (var i = 0; i < nAttempts; i++)
                {
                    es.Restart(resetBackoff);

                    sink.ExpectActions(
                        EventSink.ClosedAction(),
                        EventSink.OpenedAction(),
                        EventSink.MessageReceivedAction(anEvent)
                        );
                }
            }

            if (resetBackoff)
            {
                Assert.All(backoffs, delay => Assert.InRange(delay, TimeSpan.Zero, initialDelay));
            }
            else
            {
                AssertBackoffsAlwaysIncrease(backoffs, nAttempts);
            }
        }
        public void DefaultMethod()
        {
            var handler = new StubMessageHandler(StubResponse.StartStream());

            using (var es = MakeEventSource(handler))
            {
                _ = Task.Run(es.StartAsync);

                var req = handler.AwaitRequest();
                Assert.Equal(HttpMethod.Get, req.Method);
            }
        }
        public void LastEventIdHeaderIsSetIfConfigured()
        {
            var handler     = new StubMessageHandler(StubResponse.StartStream());
            var lastEventId = "abc123";

            using (var es = MakeEventSource(handler, builder => builder.LastEventId(lastEventId)))
            {
                _ = Task.Run(es.StartAsync);

                var req = handler.AwaitRequest();
                Assert.True(req.Headers.Contains(Constants.LastEventIdHttpHeader));
                Assert.Contains(lastEventId, req.Headers.GetValues(Constants.LastEventIdHttpHeader));
            }
        }
        public async Task When_error_handler_closes_event_source_no_reconnect_attempt_is_made()
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.WithStatus(HttpStatusCode.Unauthorized));
            handler.QueueResponse(StubResponse.StartStream());

            var evt = new EventSource(new Configuration(_uri, handler));

            evt.Error += (_, e) => evt.Close();

            await evt.StartAsync();

            Assert.Equal(1, handler.GetRequests().Count());
        }
        public async Task Default_HTTP_method_is_get()
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream());

            var evt = new EventSource(new Configuration(_uri, handler));

            handler.RequestReceived += (s, r) => evt.Close();
            await evt.StartAsync();

            var request = handler.GetRequests().First();

            Assert.Equal(HttpMethod.Get, request.Method);
        }
        public async void NoReconnectAttemptIsMadeIfErrorHandlerClosesEventSource()
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.WithStatus(HttpStatusCode.Unauthorized));
            handler.QueueResponse(StubResponse.StartStream());

            using (var es = MakeEventSource(handler))
            {
                es.Error += (_, e) => es.Close();
                await es.StartAsync();
            }

            Assert.Single(handler.GetRequests());
        }
        public void CustomMethodWithRequestBody()
        {
            var handler = new StubMessageHandler(StubResponse.StartStream());

            HttpContent        content   = new StringContent("{}");
            Func <HttpContent> contentFn = () => content;

            using (var es = MakeEventSource(handler, builder =>
                                            builder.Method(HttpMethod.Post).RequestBodyFactory(contentFn)))
            {
                _ = Task.Run(es.StartAsync);

                var req = handler.AwaitRequest();
                Assert.Equal(content, req.Content);
            }
        }
        public void ReceiveComment()
        {
            var commentSent = ": hello";

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(commentSent + "\n\n")));

            using (var es = StartEventSource(handler, out var eventSink))
            {
                eventSink.ExpectActions(
                    EventSink.OpenedAction(),
                    EventSink.CommentReceivedAction(commentSent)
                    );;
            }
        }
        public void ReceiveEventWithOnlyData()
        {
            var eventData = "this is a test message";
            var sse       = "data: " + eventData + "\n\n";

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(sse)));

            using (var es = StartEventSource(handler, out var eventSink))
            {
                eventSink.ExpectActions(
                    EventSink.OpenedAction(),
                    EventSink.MessageReceivedAction(new MessageEvent(MessageEvent.DefaultName, eventData, _uri))
                    );
            }
        }
        public async Task HTTP_method_can_be_specified()
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream());

            var config = new ConfigurationBuilder(_uri).MessageHandler(handler)
                         .Method(HttpMethod.Post).Build();
            var evt = new EventSource(config);

            handler.RequestReceived += (s, r) => evt.Close();
            await evt.StartAsync();

            var request = handler.GetRequests().First();

            Assert.Equal(HttpMethod.Post, request.Method);
        }
        public async Task When_the_HttpRequest_is_sent_then_the_outgoing_request_contains_accept_header()
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream());

            var evt = new EventSource(new Configuration(_uri, handler));

            handler.RequestReceived += (s, r) => evt.Close();

            await evt.StartAsync();

            var request = handler.GetRequests().First();

            Assert.True(request.Headers.Contains(Constants.AcceptHttpHeader));
            Assert.True(request.Headers.GetValues(Constants.AcceptHttpHeader).Contains(Constants.EventStreamContentType));
        }
        public void AcceptHeaderIsAlwaysPresent()
        {
            var handler = new StubMessageHandler(StubResponse.StartStream());

            HttpContent        content   = new StringContent("{}");
            Func <HttpContent> contentFn = () => content;

            using (var es = MakeEventSource(handler, builder =>
                                            builder.Method(HttpMethod.Post).RequestBodyFactory(contentFn)))
            {
                _ = Task.Run(es.StartAsync);

                var req = handler.AwaitRequest();
                Assert.True(req.Headers.Contains(Constants.AcceptHttpHeader));
                Assert.Contains(Constants.EventStreamContentType, req.Headers.GetValues(Constants.AcceptHttpHeader));
            }
        }
        public void ErrorForInvalidHttpStatus(HttpStatusCode statusCode)
        {
            var handler  = new StubMessageHandler();
            var response = new HttpResponseMessage(statusCode);

            handler.QueueResponse(StubResponse.WithResponse(response));

            using (var es = MakeEventSource(handler))
            {
                var eventSink = new EventSink(es, _testLogging);
                _ = Task.Run(es.StartAsync);

                var errorAction = eventSink.ExpectAction();
                var ex          = Assert.IsType <EventSourceServiceUnsuccessfulResponseException>(errorAction.Exception);
                Assert.Equal((int)statusCode, ex.StatusCode);
            }
        }
        public void ReceiveEventStreamInChunks()
        {
            // This simply verifies that chunked streaming works as expected and that events are being
            // parsed correctly regardless of how the chunks line up with the events.

            var eventData = new List <string>();
            var chunks    = new List <string>();

            for (var i = 0; i < 200; i++)
            {
                eventData.Add(string.Format("data{0}", i) + new string('x', i % 7));
            }
            var allBody = string.Concat(eventData.Select(data => "data:" + data + "\n\n"));

            for (var pos = 0; ;)
            {
                int i         = chunks.Count;
                int chunkSize = i % 20 + 1;
                if (pos + chunkSize >= allBody.Length)
                {
                    chunks.Add(allBody.Substring(pos));
                    break;
                }
                chunks.Add(allBody.Substring(pos, chunkSize));
                pos += chunkSize;
            }

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(
                                      chunks.Select(StreamAction.Write).ToArray()));

            var expectedActions = new List <EventSink.Action>();

            expectedActions.Add(EventSink.OpenedAction());
            foreach (var data in eventData)
            {
                expectedActions.Add(EventSink.MessageReceivedAction(new MessageEvent(MessageEvent.DefaultName, data, _uri)));
            }

            using (var es = StartEventSource(handler, out var eventSink))
            {
                eventSink.ExpectActions(expectedActions.ToArray());
            }
        }
        public async Task Timeout_does_not_cause_unobserved_exception()
        {
            TimeSpan readTimeout = TimeSpan.FromMilliseconds(10);
            TimeSpan timeToWait  = TimeSpan.FromMilliseconds(100);

            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.StartStream(
                                      StreamAction.Write(":\n\n").AfterDelay(timeToWait)));
            handler.QueueResponse(StubResponse.StartStream());

            var config = new ConfigurationBuilder(_uri).MessageHandler(handler).ReadTimeout(readTimeout).Build();
            var evt    = new EventSource(config);

            var caughtUnobservedException = false;
            EventHandler <UnobservedTaskExceptionEventArgs> exceptionHandler = (object sender, UnobservedTaskExceptionEventArgs e) =>
            {
                e.SetObserved();
                caughtUnobservedException = true;
            };

            TaskScheduler.UnobservedTaskException += exceptionHandler;

            try
            {
                evt.Error += (_, e) => evt.Close();

                await evt.StartAsync();

                // StartAsync has returned, meaning that the EventSource was closed by the ErrorReceiver, meaning that it
                // encountered a timeout. Wait a little bit longer to make sure that the stream reader task has got an
                // exception from the closed stream.
                Thread.Sleep(TimeSpan.FromMilliseconds(300));

                // Force finalizer to run so that if there was an unobserved exception, it will trigger that event.
                GC.Collect();
                GC.WaitForPendingFinalizers();

                Assert.False(caughtUnobservedException);
            }
            finally
            {
                TaskScheduler.UnobservedTaskException -= exceptionHandler;
            }
        }
        public async Task When_event_source_closes_do_not_dispose_configured_http_client()
        {
            var handler = new StubMessageHandler();

            handler.QueueResponse(StubResponse.WithResponse(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("Hello")
            }));

            var client = new HttpClient(handler);
            var evt    = new EventSource(new Configuration(_uri, httpClient: client));

            evt.Close();

            await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, _uri));

            client.Dispose();
        }