Example #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());
        }
Example #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");
        }
Example #5
0
        public virtual Task Send(PersistentResponse response)
        {
            HeartBeat.MarkConnection(this);

            AddTransportData(response);
            return(Send((object)response));
        }
Example #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);
        }
        public virtual void Send(PersistentResponse response)
        {
            _heartBeat.MarkConnection(this);

            AddTransportData(response);
            Send((object)response);
        }
        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());
        }
Example #9
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

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

            OnSending(data);

            return _socket.Send(data);
        }
Example #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"));
        }
Example #13
0
        public override Task Send(PersistentResponse response)
        {
            var data = JsonSerializer.Stringify(response);

            OnSending(data);

            return(_socket.Send(data));
        }
Example #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();
     }
 }
Example #16
0
        protected virtual void OnSendingResponse(PersistentResponse response)
        {
            HeartBeat.MarkConnection(this);

            if (SendingResponse != null)
            {
                SendingResponse(response);
            }
        }
 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();
     }
 }
Example #18
0
        private PersistentResponse AddTransportData(PersistentResponse response)
        {
            if (response != null)
            {
                response.TransportData["LongPollDelay"] = LongPollDelay;
            }

            return(response);
        }
Example #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));
        }
Example #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());
        }
Example #21
0
 private void AddTransportData(PersistentResponse response)
 {
     if (LongPollDelay > 0)
     {
         if (response.TransportData == null)
         {
             response.TransportData = new Dictionary <string, object>();
         }
         response.TransportData["LongPollDelay"] = LongPollDelay;
     }
 }
Example #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);
        }
Example #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);
        }
Example #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);
            }
        }
        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);
        }
Example #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);
        }
        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;
        }
        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());
        }
        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());
        }
Example #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());
        }
Example #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));
        }
Example #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);
            }
        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;
        }
        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();
            }
        }
Example #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());
        }
Example #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);
        }
Example #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();
            }
        }
Example #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);
            }
        }
        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)));
            }
        }
        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());
        }
        private PersistentResponse AddTransportData(PersistentResponse response)
        {
            if (response != null)
            {
                response.TransportData["LongPollDelay"] = LongPollDelay;
            }

            return response;
        }
        public virtual Task Send(PersistentResponse response)
        {
            _heartBeat.MarkConnection(this);

            AddTransportData(response);
            return Send((object)response);
        }
Example #45
0
 public virtual Task Send(PersistentResponse response)
 {
     HeartBeat.MarkConnection(this);
     var data = _jsonSerializer.Stringify(response);
     OnSending(data);
     return Context.Response.WriteAsync(data);
 }
        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);
        }
Example #48
0
 public override Task Send(PersistentResponse response)
 {
     return Send((object)response);
 }
Example #49
0
 public virtual void Send(PersistentResponse response)
 {
     Send((object)response);
 }
 private void AddTransportData(PersistentResponse response)
 {
     if (LongPollDelay > 0)
     {
         if (response.TransportData == null)
         {
             response.TransportData = new Dictionary<string, object>();
         }
         response.TransportData["LongPollDelay"] = LongPollDelay;
     }
 }
Example #51
0
 public abstract Task Send(PersistentResponse response);
Example #52
0
        public virtual Task Send(PersistentResponse response)
        {
            var data = _jsonSerializer.Stringify(response);

            OnSending(data);

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

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

            OnSending(data);

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

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

            AddTransportData(response);

            return Send((object)response);
        }