예제 #1
0
        public void WriteJsonWritesSkipsCommands()
        {
            // Arrange
            var writer   = new StringWriter();
            var response = new PersistentResponse(m => false);

            response.Messages                = new List <ArraySegment <Message> >();
            response.TransportData           = new Dictionary <string, object>();
            response.TransportData["Groups"] = new List <string>
            {
                "g1"
            };
            response.MessageId = "Baz";
            response.Messages.Add(new ArraySegment <Message>(new[] { new Message("1", "key", "value1")
                                                                     {
                                                                         CommandId = "something"
                                                                     },
                                                                     new Message("1", "key2", "value2") }, 0, 2));

            // Act
            ((IJsonWritable)response).WriteJson(writer);

            // Assert
            Assert.Equal(@"{""MessageId"":""Baz"",""Disconnect"":false,""TimedOut"":false,""TransportData"":{""Groups"":[""g1""]},""Messages"":[value2]}", writer.ToString());
        }
예제 #2
0
            public void GroupTokenIsNotNullWhenGroupsChangeToEmpty()
            {
                var response = new PersistentResponse();
                var groupSet = new DiffSet <string>(new string[] { "b", "d" });

                groupSet.DetectChanges();

                groupSet.Remove("b");
                groupSet.Remove("d");

                var serializer    = JsonUtility.CreateDefaultSerializer();
                var protectedData = new Mock <IProtectedData>();

                protectedData.Setup(m => m.Protect(It.IsAny <string>(), It.IsAny <string>()))
                .Returns <string, string>((value, purpose) => value);

                protectedData.Setup(m => m.Unprotect(It.IsAny <string>(), It.IsAny <string>()))
                .Returns <string, string>((value, purpose) => value);

                Connection.PopulateResponseState(response, groupSet, serializer, protectedData.Object, connectionId: "myconnection");

                Assert.NotNull(response.GroupsToken);
                var parts = response.GroupsToken.Split(new[] { ':' }, 2);

                Assert.Equal(2, parts.Length);
                Assert.Equal("myconnection", parts[0]);
                var groups = serializer.Deserialize <string[]>(new JsonTextReader(new StringReader(parts[1])));

                Assert.Equal(0, groups.Length);
            }
        public void RequestWithMessageIdCallsReceiveOnConnectionThenSend()
        {
            var context  = new Mock <HttpContextBase>();
            var request  = new Mock <HttpRequestBase>();
            var response = new Mock <HttpResponseBase>();

            request.Setup(m => m.Path).Returns("/foo");
            request.Setup(m => m["clientId"]).Returns("1");
            request.Setup(m => m["messageId"]).Returns("20");
            context.Setup(m => m.Response).Returns(response.Object);
            context.Setup(m => m.Request).Returns(request.Object);
            var json      = new Mock <IJsonStringifier>();
            var heartBeat = new Mock <ITransportHeartBeat>();
            var transport = new Mock <LongPollingTransport>(context.Object, json.Object, heartBeat.Object)
            {
                CallBase = true
            };
            var connection = new Mock <IConnection>();
            PersistentResponse persistentResponse = null;

            connection.Setup(m => m.ReceiveAsync(20)).Returns(TaskAsyncHelper.FromResult <PersistentResponse>(persistentResponse));

            transport.Object.ProcessRequest(connection.Object)().Wait();

            heartBeat.Verify(m => m.AddConnection(transport.Object), Times.Once());
            heartBeat.Verify(m => m.RemoveConnection(transport.Object), Times.Once());
            connection.Verify(m => m.ReceiveAsync(20), Times.Once());
            transport.Verify(m => m.Send(persistentResponse), Times.Once());
            response.VerifySet(m => m.ContentType = "application/json");
            response.Verify(m => m.Write(It.IsAny <string>()), Times.Once());
            json.Verify(m => m.Stringify(persistentResponse), Times.Once());
        }
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);
            OnSending(data);

            return Context.Response.WriteAsync("id: " + response.MessageId + "\n" + "data: " + data + "\n\n");
        }
예제 #5
0
        public virtual Task Send(PersistentResponse response)
        {
            HeartBeat.MarkConnection(this);

            AddTransportData(response);
            return(Send((object)response));
        }
예제 #6
0
        private PersistentResponse GetResponse(MessageResult result)
        {
            // Do a single sweep through the results to process commands and extract values
            ProcessResults(result);

            Debug.Assert(WriteCursor != null, "Unable to resolve the cursor since the method is null");

            var response = new PersistentResponse(ExcludeMessage, WriteCursor);

            response.Terminal = result.Terminal;

            if (!result.Terminal)
            {
                // Only set these properties if the message isn't terminal
                response.Messages   = result.Messages;
                response.Disconnect = _disconnected;
                response.Aborted    = _aborted;
                response.TotalCount = result.TotalCount;
            }

            PopulateResponseState(response);

            _counters.ConnectionMessagesReceivedTotal.IncrementBy(result.TotalCount);
            _counters.ConnectionMessagesReceivedPerSec.IncrementBy(result.TotalCount);

            return(response);
        }
예제 #7
0
        public virtual void Send(PersistentResponse response)
        {
            _heartBeat.MarkConnection(this);

            AddTransportData(response);
            Send((object)response);
        }
예제 #8
0
        public void ConnectRequestCallsReceiveOnConnectionThenSend()
        {
            var context  = new Mock <HttpContextBase>();
            var request  = new Mock <HttpRequestBase>();
            var response = new Mock <HttpResponseBase>();

            request.Setup(m => m.Path).Returns("/foo/connect");
            var qs = new NameValueCollection();

            qs["connectionId"] = "1";
            request.Setup(m => m.QueryString).Returns(qs);
            context.Setup(m => m.Response).Returns(response.Object);
            context.Setup(m => m.Request).Returns(request.Object);
            var json      = new Mock <IJsonSerializer>();
            var heartBeat = new Mock <ITransportHeartBeat>();
            var transport = new Mock <LongPollingTransport>(context.Object, json.Object, heartBeat.Object)
            {
                CallBase = true
            };
            var connection = new Mock <IConnection>();
            PersistentResponse persistentResponse = null;

            connection.Setup(m => m.ReceiveAsync()).Returns(TaskAsyncHelper.FromResult <PersistentResponse>(persistentResponse));

            transport.Object.ProcessRequest(connection.Object)().Wait();

            heartBeat.Verify(m => m.AddConnection(transport.Object), Times.Once());
            connection.Verify(m => m.ReceiveAsync(), Times.Once());
            transport.Verify(m => m.Send(persistentResponse), Times.Once());
            response.VerifySet(m => m.ContentType = "application/json");
            response.Verify(m => m.Write(It.IsAny <string>()), Times.Once());
            json.Verify(m => m.Stringify(persistentResponse), Times.Once());
        }
예제 #9
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            return(_socket.Send(data).Catch(IncrementErrorCounters));
        }
예제 #10
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            return _socket.Send(data);
        }
예제 #11
0
        public virtual Task Send(PersistentResponse response)
        {
            HeartBeat.MarkConnection(this);
            var data = _jsonSerializer.Stringify(response);

            OnSending(data);
            return(Context.Response.WriteAsync(data));
        }
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            return(Context.Response.WriteAsync("id: " + response.MessageId + "\n" + "data: " + data + "\n\n"));
        }
예제 #13
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            return(_socket.Send(data));
        }
예제 #14
0
        public virtual Task Send(PersistentResponse response)
        {
            var data = _jsonSerializer.Stringify(response);

            OnSending(data);

            return(Context.Response.WriteAsync(data));
        }
 public override void Send(PersistentResponse response)
 {
     Context.Response.Write("id: " + response.MessageId + "\n");
     Context.Response.Write("data: " + JsonSerializer.Stringify(response) + "\n\n");
     if (Context.Response.IsClientConnected)
     {
         Context.Response.Flush();
     }
 }
예제 #16
0
        protected virtual void OnSendingResponse(PersistentResponse response)
        {
            HeartBeat.MarkConnection(this);

            if (SendingResponse != null)
            {
                SendingResponse(response);
            }
        }
예제 #17
0
 public override void Send(PersistentResponse response)
 {
     Context.Response.Write("id: " + response.MessageId + "\n");
     Context.Response.Write("data: " + JsonSerializer.Stringify(response) + "\n\n");
     if (Context.Response.IsClientConnected)
     {
         Context.Response.Flush();
     }
 }
예제 #18
0
        private PersistentResponse AddTransportData(PersistentResponse response)
        {
            if (response != null)
            {
                response.TransportData["LongPollDelay"] = LongPollDelay;
            }

            return(response);
        }
예제 #19
0
        public override Task Send(PersistentResponse response)
        {
            OnSendingResponse(response);

            OutputWriter.Write("<script>r(c, ");
            JsonSerializer.Serialize(response, OutputWriter);
            OutputWriter.Write(");</script>\r\n");
            OutputWriter.Flush();

            return(Context.Response.FlushAsync().Catch(IncrementErrorCounters));
        }
예제 #20
0
        public override Task Send(PersistentResponse response)
        {
            OnSendingResponse(response);

            OutputWriter.Write("<script>r(c, ");
            JsonSerializer.Stringify(response, OutputWriter);
            OutputWriter.Write(");</script>\r\n");
            OutputWriter.Flush();

            return(Context.Response.FlushAsync());
        }
예제 #21
0
 private void AddTransportData(PersistentResponse response)
 {
     if (LongPollDelay > 0)
     {
         if (response.TransportData == null)
         {
             response.TransportData = new Dictionary <string, object>();
         }
         response.TransportData["LongPollDelay"] = LongPollDelay;
     }
 }
예제 #22
0
        public override Task Send(PersistentResponse response)
        {
            OnSendingResponse(response);

            OutputWriter.Write("<script>r(c, ");
            JsonSerializer.Serialize(response, OutputWriter);
            OutputWriter.Write(");</script>\r\n");
            OutputWriter.Flush();

            return Context.Response.FlushAsync().Catch(IncrementErrorCounters);
        }
예제 #23
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);
            OnSending(data);

            if (Context.Response.IsClientConnected)
            {
                return Context.Response.WriteAsync("id: " + response.MessageId + "\n" + "data: " + data + "\n\n");
            }
            return TaskAsyncHelper.Empty;
        }
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            if (Context.Response.IsClientConnected)
            {
                return(Context.Response.WriteAsync("id: " + response.MessageId + "\n" + "data: " + data + "\n\n"));
            }
            return(TaskAsyncHelper.Empty);
        }
예제 #25
0
        private async Task ProcessMessages(IConnection connection)
        {
            long?lastMessageId = null;

            while (!_connectionTokenSource.IsCancellationRequested)
            {
                PersistentResponse response = lastMessageId == null ? await connection.ReceiveAsync() : await connection.ReceiveAsync(lastMessageId.Value);

                lastMessageId = response.MessageId;
                Send(response);
            }
        }
예제 #26
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);
            OnSending(data);

            var script = "<script>r(c, " + data + ");</script>\r\n";
            if (_isDebug)
            {
                script += "<div>" + data + "</div>\r\n";
            }

            return Context.Response.WriteAsync(script);
        }
예제 #27
0
        private static PersistentResponse GetWrappedResponse(string raw)
        {
            var data    = Encoding.Default.GetBytes(raw);
            var message = new Message("foo", "key", new ArraySegment <byte>(data));

            var response = new PersistentResponse
            {
                Messages = new List <ArraySegment <Message> >
                {
                    new ArraySegment <Message>(new Message[] { message })
                }
            };

            return(response);
        }
예제 #28
0
        public override Task Send(PersistentResponse response)
        {
            OnSendingResponse(response);

            OutputWriter.Write("id: ");
            OutputWriter.Write(response.MessageId);
            OutputWriter.WriteLine();
            OutputWriter.Write("data: ");
            JsonSerializer.Serialize(response, OutputWriter);
            OutputWriter.WriteLine();
            OutputWriter.WriteLine();
            OutputWriter.Flush();

            return Context.Response.FlushAsync().Catch(IncrementErrorCounters);
        }
        public override Task Send(PersistentResponse response)
        {
            OnSendingResponse(response);

            OutputWriter.Write("id: ");
            OutputWriter.Write(response.MessageId);
            OutputWriter.WriteLine();
            OutputWriter.Write("data: ");
            JsonSerializer.Stringify(response, OutputWriter);
            OutputWriter.WriteLine();
            OutputWriter.WriteLine();
            OutputWriter.Flush();

            return TaskAsyncHelper.Empty;
        }
예제 #30
0
        public override Task Send(PersistentResponse response)
        {
            OnSendingResponse(response);

            OutputWriter.Write("id: ");
            OutputWriter.Write(response.MessageId);
            OutputWriter.WriteLine();
            OutputWriter.Write("data: ");
            JsonSerializer.Stringify(response, OutputWriter);
            OutputWriter.WriteLine();
            OutputWriter.WriteLine();
            OutputWriter.Flush();

            return(Context.Response.FlushAsync());
        }
예제 #31
0
        public void WriteJsonSkipsNullTransportDaa()
        {
            // Arrange
            var writer = new StringWriter();
            var response = new PersistentResponse(m => m.Key == "key2");
            response.Messages = new List<ArraySegment<Message>>();
            response.MessageId = "Baz";
            response.Messages.Add(new ArraySegment<Message>(new[] { new Message("1", "key", "value1"),
                                                                    new Message("1", "key2", "value2") }, 0, 2));

            // Act
            ((IJsonWritable)response).WriteJson(writer);

            // Assert
            Assert.Equal(@"{""MessageId"":""Baz"",""Disconnect"":false,""TimedOut"":false,""Messages"":[value1]}", writer.ToString());
        }
예제 #32
0
        public void WriteJsonSkipsNullTransportDaa()
        {
            // Arrange
            var writer   = new StringWriter();
            var response = new PersistentResponse(m => m.Key == "key2");

            response.Messages  = new List <ArraySegment <Message> >();
            response.MessageId = "Baz";
            response.Messages.Add(new ArraySegment <Message>(new[] { new Message("1", "key", "value1"),
                                                                     new Message("1", "key2", "value2") }, 0, 2));

            // Act
            ((IJsonWritable)response).WriteJson(writer);

            // Assert
            Assert.Equal(@"{""MessageId"":""Baz"",""Disconnect"":false,""TimedOut"":false,""Messages"":[value1]}", writer.ToString());
        }
예제 #33
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            data = EscapeAnyInlineScriptTags(data);

            var script = "<script>r(c, " + data + ");</script>\r\n";

            if (_isDebug)
            {
                script += "<div>" + data + "</div>\r\n";
            }

            return(Context.Response.WriteAsync(script));
        }
예제 #34
0
            public void GroupTokenIsNullWhenNoGroups()
            {
                var response      = new PersistentResponse();
                var groupSet      = new DiffSet <string>(new string[] { });
                var serializer    = new JsonNetSerializer();
                var protectedData = new Mock <IProtectedData>();

                protectedData.Setup(m => m.Protect(It.IsAny <string>(), It.IsAny <string>()))
                .Returns <string, string>((value, purpose) => value);

                protectedData.Setup(m => m.Unprotect(It.IsAny <string>(), It.IsAny <string>()))
                .Returns <string, string>((value, purpose) => value);

                Connection.PopulateResponseState(response, groupSet, serializer, protectedData.Object, connectionId: null);

                Assert.Null(response.GroupsToken);
            }
예제 #35
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);
            OnSending(data);

            var script = String.Format(_sendTemplate, data);
            if (_isDebug)
            {
                script += (String.Format(_debugTemplate, data));
            }

            if (Context.Response.IsClientConnected)
            {
                return Context.Response.WriteAsync(script);
            }
            return TaskAsyncHelper.Empty;
        }
예제 #36
0
        public override void Send(PersistentResponse response)
        {
            var payload = JsonSerializer.Stringify(response);
            OnSending(payload);

            var script = String.Format(_sendTemplate, payload);
            Context.Response.Write(script);

            if (_isDebug)
            {
                Context.Response.Write(String.Format(_debugTemplate, payload));
            }

            if (Context.Response.IsClientConnected)
            {
                Context.Response.Flush();
            }
        }
예제 #37
0
        public void WriteJsonSkipsNullGroups()
        {
            // Arrange
            var writer   = new StringWriter();
            var response = new PersistentResponse(m => m.Key == "key2", w =>
            {
                w.Write("Baz");
            });

            response.Messages = new List <ArraySegment <Message> >();
            response.Messages.Add(new ArraySegment <Message>(new[] { new Message("1", "key", "value1"),
                                                                     new Message("1", "key2", "value2") }, 0, 2));

            // Act
            ((IJsonWritable)response).WriteJson(writer);

            // Assert
            Assert.Equal(@"{""C"":""Baz"",""M"":[value1]}", writer.ToString());
        }
예제 #38
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            var script = String.Format(_sendTemplate, data);

            if (_isDebug)
            {
                script += (String.Format(_debugTemplate, data));
            }

            if (Context.Response.IsClientConnected)
            {
                return(Context.Response.WriteAsync(script));
            }
            return(TaskAsyncHelper.Empty);
        }
예제 #39
0
        public override void Send(PersistentResponse response)
        {
            var payload = JsonSerializer.Stringify(response);

            OnSending(payload);

            var script = String.Format(_sendTemplate, payload);

            Context.Response.Write(script);

            if (_isDebug)
            {
                Context.Response.Write(String.Format(_debugTemplate, payload));
            }

            if (Context.Response.IsClientConnected)
            {
                Context.Response.Flush();
            }
        }
예제 #40
0
        internal static void PopulateResponseState(PersistentResponse response,
                                                   DiffSet <string> groupSet,
                                                   IJsonSerializer serializer,
                                                   IProtectedData protectedData,
                                                   string connectionId)
        {
            bool anyChanges = groupSet.DetectChanges();

            if (anyChanges)
            {
                // Create a protected payload of the sorted list
                IEnumerable <string> groups = groupSet.GetSnapshot();

                // Remove group prefixes before any thing goes over the wire
                string groupsString = connectionId + ':' + serializer.Stringify(PrefixHelper.RemoveGroupPrefixes(groups));;

                // The groups token
                response.GroupsToken = protectedData.Protect(groupsString, Purposes.Groups);
            }
        }
예제 #41
0
        private ReadOnlyMemory <byte> GetPayload(Message message)
        {
            IJsonWritable value = new PersistentResponse(m => false, tw => tw.Write("0"))
            {
                Messages = new List <ArraySegment <Message> >
                {
                    new ArraySegment <Message>(new[] { message })
                },
                TotalCount = 1
            };

            using (var writer = new MemoryPoolTextWriter(_pool))
            {
                value.WriteJson(writer);
                writer.Flush();

                // Reuse ConnectionDataMessage to wrap the payload
                return(_serviceProtocol.GetMessageBytes(new ConnectionDataMessage(string.Empty, writer.Buffer)));
            }
        }
예제 #42
0
        public void WriteJsonWritesSkipsCommands()
        {
            // Arrange
            var writer = new StringWriter();
            var response = new PersistentResponse(m => false);
            response.Messages = new List<ArraySegment<Message>>();
            response.TransportData = new Dictionary<string, object>();
            response.TransportData["Groups"] = new List<string>
            {
                "g1"
            };
            response.MessageId = "Baz";
            response.Messages.Add(new ArraySegment<Message>(new[] { new Message("1", "key", "value1") { CommandId = "something"},
                                                                    new Message("1", "key2", "value2") }, 0, 2));

            // Act
            ((IJsonWritable)response).WriteJson(writer);

            // Assert
            Assert.Equal(@"{""MessageId"":""Baz"",""Disconnect"":false,""TimedOut"":false,""TransportData"":{""Groups"":[""g1""]},""Messages"":[value2]}", writer.ToString());
        }
예제 #43
0
        private PersistentResponse AddTransportData(PersistentResponse response)
        {
            if (response != null)
            {
                response.TransportData["LongPollDelay"] = LongPollDelay;
            }

            return response;
        }
예제 #44
0
        public virtual Task Send(PersistentResponse response)
        {
            _heartBeat.MarkConnection(this);

            AddTransportData(response);
            return Send((object)response);
        }
예제 #45
0
 public virtual Task Send(PersistentResponse response)
 {
     HeartBeat.MarkConnection(this);
     var data = _jsonSerializer.Stringify(response);
     OnSending(data);
     return Context.Response.WriteAsync(data);
 }
예제 #46
0
        public void Send(PersistentResponse response)
        {
            TransportHeartBeat.Instance.RemoveConnection(this);

            AddTransportData(response);
            Send((object)response);
        }
        public virtual void Send(PersistentResponse response)
        {
            _heartBeat.RemoveConnection(this);

            AddTransportData(response);
            Send((object)response);
        }
예제 #48
0
 public override Task Send(PersistentResponse response)
 {
     return Send((object)response);
 }
예제 #49
0
 public virtual void Send(PersistentResponse response)
 {
     Send((object)response);
 }
예제 #50
0
 private void AddTransportData(PersistentResponse response)
 {
     if (LongPollDelay > 0)
     {
         if (response.TransportData == null)
         {
             response.TransportData = new Dictionary<string, object>();
         }
         response.TransportData["LongPollDelay"] = LongPollDelay;
     }
 }
예제 #51
0
 public abstract Task Send(PersistentResponse response);
예제 #52
0
        public virtual Task Send(PersistentResponse response)
        {
            var data = _jsonSerializer.Stringify(response);

            OnSending(data);

            return Context.Response.WriteAsync(data);
        }
예제 #53
0
        protected virtual void OnSendingResponse(PersistentResponse response)
        {
            HeartBeat.MarkConnection(this);

            if (SendingResponse != null)
            {
                SendingResponse(response);
            }
        }
예제 #54
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            return _socket.Send(data).Catch(IncrementErrorCounters);
        }
예제 #55
0
        public virtual Task Send(PersistentResponse response)
        {
            HeartBeat.MarkConnection(this);

            if (SendingResponse != null)
            {
                SendingResponse(response);
            }

            AddTransportData(response);

            return Send((object)response);
        }