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_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_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 Connection_closed_before_threshold_gets_increasing_backoff_delay()
        {
            TimeSpan  threshold  = TimeSpan.FromSeconds(1);
            TimeSpan  closeDelay = TimeSpan.FromMilliseconds(100);
            const int nAttempts  = 3;

            var handler = new StubMessageHandler();

            for (var i = 0; i < nAttempts; i++)
            {
                handler.QueueResponse(StubResponse.StartStream(
                                          StreamAction.CloseStream().AfterDelay(closeDelay)));
            }
            handler.QueueResponse(StubResponse.StartStream());

            var config = new ConfigurationBuilder(_uri).MessageHandler(handler)
                         .BackoffResetThreshold(threshold).Build();
            var evt = new EventSource(config);

            var requestTimes = new List <DateTime>();

            handler.RequestReceived += (_, r) =>
            {
                requestTimes.Add(DateTime.Now);
                if (requestTimes.Count > nAttempts)
                {
                    evt.Close();
                }
            };

            await evt.StartAsync();

            Assert.Equal(nAttempts + 1, handler.GetRequests().Count());

            for (var i = 0; i < nAttempts; i++)
            {
                var interval = requestTimes[i + 1] - requestTimes[i] - closeDelay;
                var min      = (i == 0) ? TimeSpan.Zero : GetMaxBackoffDelayForAttempt(config, i);
                var max      = GetMaxBackoffDelayForAttempt(config, i + 1);
                AssertTimeSpanInRange(interval, min, max);
            }
        }
        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"));
            }
        }
        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));
        }
 private static StubMessageHandler HandlerWithBasicEvent() =>
 new StubMessageHandler(StubResponse.StartStream(StreamAction.Write(BasicEvent)));