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); }
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 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 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); }
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 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 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 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 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 void ReceiveEventWithID() { var eventName = "test event"; var eventData = "this is a test message"; var eventId = "123abc"; var sse = "event: " + eventName + "\ndata: " + eventData + "\nid: " + eventId + "\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(eventName, eventData, eventId, _uri)) ); } }
public async Task When_an_message_SSE_contains_id_is_received_then_last_event_id_is_set() { var sse = "id:200\nevent: put\ndata: this is a test message\n\n"; var handler = new StubMessageHandler(); handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(sse))); var evt = new EventSource(new Configuration(_uri, handler)); var m = new MessageReceiver(); evt.MessageReceived += m; evt.MessageReceived += ((_, e) => evt.Close()); await evt.StartAsync(); Assert.Equal("200", m.RequireSingleEvent().Message.LastEventId); }
public async Task When_an_event_message_SSE_is_received_then_a_message_event_is_raised() { var sse = "event: put\ndata: this is a test message\n\n"; var handler = new StubMessageHandler(); handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(sse))); var evt = new EventSource(new Configuration(_uri, handler)); var m = new MessageReceiver(); evt.MessageReceived += m; evt.MessageReceived += ((_, e) => evt.Close()); await evt.StartAsync(); Assert.Equal("put", m.RequireSingleEvent().EventName); }
public async Task When_reconnecting_the_outgoing_request_overrides_Last_Event_Id_from_configuration() { 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 configuration = Configuration .Builder(_uri) .MessageHandler(handler) .LastEventId("0") .RequestHeader(Constants.LastEventIdHttpHeader, "0") .Build(); var evt = new EventSource(configuration); var first = true; handler.RequestReceived += (s, r) => { if (first) { first = false; } else { evt.Close(); } }; await evt.StartAsync(); var requests = handler.GetRequests().ToList(); Assert.True(requests[0].Headers.Contains(Constants.LastEventIdHttpHeader)); Assert.True(requests[1].Headers.Contains(Constants.LastEventIdHttpHeader)); var lastEventIdHeader = requests[1].Headers.GetValues(Constants.LastEventIdHttpHeader).ToArray(); Assert.Equal(1, lastEventIdHeader.Length); Assert.Equal(lastEventId, lastEventIdHeader[0]); }
public async Task When_a_comment_SSE_is_received_then_a_comment_event_is_raised() { var commentSent = ": hello"; var handler = new StubMessageHandler(); handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(commentSent + "\n\n"))); var evt = new EventSource(new Configuration(_uri, handler)); string commentReceived = null; evt.CommentReceived += (_, e) => { commentReceived = e.Comment; evt.Close(); }; await evt.StartAsync(); Assert.Equal(commentSent, commentReceived); }
public async Task When_response_does_not_exceed_read_timeout_then_expected_message_event_occurs() { var sse = "event: put\ndata: this is a test message\n\n"; TimeSpan readTimeout = TimeSpan.FromSeconds(4); TimeSpan timeToWait = readTimeout.Subtract(TimeSpan.FromSeconds(1)); var handler = new StubMessageHandler(); handler.QueueResponse(StubResponse.StartStream( StreamAction.Write(sse).AfterDelay(timeToWait))); var config = new ConfigurationBuilder(_uri).MessageHandler(handler).ReadTimeout(readTimeout).Build(); var evt = new EventSource(config); var receiver = new MessageReceiver(); evt.MessageReceived += receiver; evt.MessageReceived += (_, e) => evt.Close(); await evt.StartAsync(); Assert.Equal("put", receiver.RequireSingleEvent().EventName); }
public void SendMostRecentEventIdOnReconnect() { var initialEventId = "abc123"; var eventId1 = "xyz456"; var message1 = new MessageEvent("put", "this is a test message", eventId1, _uri); var handler = new StubMessageHandler(); handler.QueueResponse(StubResponse.StartStream(StreamAction.Write(message1), StreamAction.CloseStream())); handler.QueueResponse(StubResponse.StartStream()); using (var es = MakeEventSource(handler, builder => builder.InitialRetryDelay(TimeSpan.FromMilliseconds(20)) .LastEventId(initialEventId))) { var eventSink = new EventSink(es, _testLogging); _ = Task.Run(es.StartAsync); var req1 = handler.AwaitRequest(); Assert.Contains(initialEventId, req1.Headers.GetValues("Last-Event-Id")); var req2 = handler.AwaitRequest(); Assert.Contains(eventId1, req2.Headers.GetValues("Last-Event-Id")); } }
private static StubMessageHandler HandlerWithBasicEvent() => new StubMessageHandler(StubResponse.StartStream(StreamAction.Write(BasicEvent)));