Manages performance counters using Windows performance counters.
Inheritance: IPerformanceCounterManager
Example #1
0
        public void SendAfterOpenAndAfterErrorThrows()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            int x = 0;

            var firstSend = stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                                        null);

            stream.Open();

            // Wait on the first send to drain
            firstSend.Wait();

            stream.SetError(new Exception("Failed"));

            Assert.Throws <Exception>(() =>
            {
                stream.Send(_ =>
                {
                    x++;
                    return(TaskAsyncHelper.Empty);
                },
                            null).Wait();
            });

            Assert.Equal(1, x);
        }
        public void CloseWhileQueueRunsWithFailedTask()
        {
            int x             = 0;
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                await TaskAsyncHelper.FromError(new Exception());
            },
                        null);
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);
            stream.Close();
            Assert.Equal(1, x);
        }
Example #3
0
        public void InitialToClosed()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Close();
        }
        public void SendAfterOpenAndAfterErrorThrows()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            int x = 0;

            var firstSend = stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            stream.Open();
            
            // Wait on the first send to drain
            firstSend.Wait();

            stream.SetError(new Exception("Failed"));

            Assert.Throws<Exception>(() =>
            {
                stream.Send(_ =>
                {
                    x++;
                    return TaskAsyncHelper.Empty;
                },
                null).Wait();
            });

            Assert.Equal(1, x);
        }
 public void CloseWhileQueueRunsWithFailedTask()
 {
     int x = 0;
     var loggerFactory = new Mock<ILoggerFactory>();
     var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
     var logger = new Mock<ILogger>();
     var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);
     stream.Open();
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         x++;
     },
     null);
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         await TaskAsyncHelper.FromError(new Exception());
     },
     null);
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         x++;
     },
     null);
     stream.Close();
     Assert.Equal(1, x);
 }
Example #6
0
        public void SendsBeforeOpenedRunOnceOpenedWhenQueuingBehaviorInitialOnly()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            int x = 0;

            stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                        null);

            Task task = stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                                    null);

            stream.Open();

            task.Wait();

            Assert.Equal(2, x);
        }
        public void OpenAfterErrorRunsQueue()
        {
            int x             = 0;
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(_ => { throw new InvalidOperationException(); }, null);

            stream.Open();

            stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                        null);

            var task = stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                                   null);

            task.Wait();

            Assert.Equal(2, x);
        }
Example #8
0
        public void EnqueueWithoutOpenRaisesOnError()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);

            Assert.Throws<InvalidOperationException>(() => stream.Send(_ => { throw new InvalidOperationException(); }, null));
        }
        public void SendAfterOpenAndAfterErrorThrows()
        {
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            int x = 0;

            var firstSend = stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                                        null);

            stream.Open();

            // Wait on the first send to drain
            firstSend.Wait();

            stream.SetError(new Exception("Failed"));

            Assert.Throws <Exception>(() =>
            {
                stream.Send(_ =>
                {
                    x++;
                    return(TaskAsyncHelper.Empty);
                },
                            null).Wait();
            });

            Assert.Equal(1, x);
        }
Example #10
0
        public void CloseWhileQueueRunsWithFailedTask()
        {
            int x            = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                await TaskAsyncHelper.FromError(new Exception());
            },
                        null);
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);
            stream.Close();
            Assert.Equal(1, x);
        }
        public void SendsBeforeOpenedRunOnceOpenedWhenQueuingBehaviorInitialOnly()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.InitialOnly, 1000, perfCounters);
            
            int x = 0;

            stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            Task task = stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            stream.Open();

            task.Wait();
            
            Assert.Equal(2, x);
        }
Example #12
0
        public void CloseWhileQueueRuns()
        {
            int x            = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);

            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);
            stream.Close();
            Assert.Equal(3, x);
        }
Example #13
0
 public void CloseWhileQueueRuns()
 {
     int x = 0;
     var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
     var stream = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);
     stream.Open();
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         x++;
     },
     null);
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         x++;
     },
     null);
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         x++;
     },
     null);
     stream.Close();
     Assert.Equal(3, x);
 }
Example #14
0
        public void OpenAfterErrorRunsQueue()
        {
            int x = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);
            stream.Open();
            stream.Send(_ => { throw new InvalidOperationException(); }, null);

            stream.Open();

            stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            var task = stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            task.Wait();

            Assert.Equal(2, x);
        }
Example #15
0
        public void OpenAfterErrorRunsQueue()
        {
            int x            = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(_ => { throw new InvalidOperationException(); }, null);

            stream.Open();

            stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                        null);

            var task = stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                                   null);

            Assert.True(task.Wait(10000));

            Assert.Equal(2, x);
        }
Example #16
0
        public void EnqueueWithoutOpenRaisesOnError()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);

            Assert.Throws <InvalidOperationException>(() => stream.Send(_ => { throw new InvalidOperationException(); }, null));
        }
        public void SendsBeforeOpenedRunOnceOpenedWhenQueuingBehaviorInitialOnly()
        {
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            int x = 0;

            stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                        null);

            Task task = stream.Send(_ =>
            {
                x++;
                return(TaskAsyncHelper.Empty);
            },
                                    null);

            stream.Open();

            task.Wait();

            Assert.Equal(2, x);
        }
Example #18
0
 public void BufferAfterClosedEnqueueThrows()
 {
     var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
     var stream = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);
     stream.Close();
     stream.SetError(new Exception());
     Assert.Throws<Exception>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
 }
        public void InitialToClosed()
        {
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Close();
        }
Example #20
0
        public async Task BufferAfterClosedEnqueueThrows()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Close();
            stream.SetError(new Exception());
            await Assert.ThrowsAsync <Exception>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
Example #21
0
        public void OpenAfterClosedEnqueueThrows()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);

            stream.Close();
            stream.Open();
            Assert.Throws <InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
 public void BufferAfterClosedEnqueueThrows()
 {
     var loggerFactory = new Mock<ILoggerFactory>();
     var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
     var logger = new Mock<ILogger>();
     var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);
     stream.Close();
     stream.SetError(new Exception());
     Assert.ThrowsAsync<Exception>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
 }
 public void GroupThrowsNullExceptionWhenGroupNameIsNull()
 {
     var serializer = JsonUtility.CreateDefaultSerializer();
     var counters = new PerformanceCounterManager();
     var connection = new Mock<IConnection>();
     var invoker = new Mock<IHubPipelineInvoker>();
     var hubContext = new HubContext(connection.Object, invoker.Object, "test");
     
     Assert.Throws<ArgumentException>(() => hubContext.Clients.Group(null));
 }
Example #24
0
        public async Task SendBeforeOpenDoesNotThrowWhenQueuingBehaviorInitialOnly()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            var sendTask = stream.Send(_ => { return(TaskAsyncHelper.Empty); }, null);

            stream.Open();

            await sendTask.OrTimeout();
        }
        public void BufferAfterClosedEnqueueThrows()
        {
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Close();
            stream.SetError(new Exception());
            Assert.ThrowsAsync <Exception>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
        public void SendBeforeOpenDoesNotThrowWhenQueuingBehaviorInitialOnly()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            var sendTask = stream.Send(_ => { return TaskAsyncHelper.Empty; }, null);

            stream.Open();

            Assert.DoesNotThrow(() => sendTask.Wait());
        }
Example #27
0
        public void SendAfterCloseThenOpenRemainsClosed()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(_ => Task.Delay(50), null);
            stream.Close();
            stream.Open();
            Assert.Throws <InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
        public void SendBeforeOpenDoesNotThrowWhenQueuingBehaviorInitialOnly()
        {
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            var sendTask = stream.Send(_ => { return(TaskAsyncHelper.Empty); }, null);

            stream.Open();

            Assert.DoesNotThrow(() => sendTask.Wait());
        }
        public void SendAfterCloseThenOpenRemainsClosed()
        {
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(_ => Task.Delay(50), null);
            stream.Close();
            stream.Open();
            Assert.ThrowsAsync <InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
Example #30
0
        public async Task FarmDisconnectRaisesUncleanDisconnects()
        {
            // Each node shares the same bus but are independent servers
            const int nodeCount            = 3;
            var       counters             = new PerformanceCounterManager();
            var       configurationManager = new DefaultConfigurationManager();

            configurationManager.DisconnectTimeout = TimeSpan.FromSeconds(6);

            using (EnableDisposableTracing())
                using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000))
                    using (var loadBalancer = new LoadBalancer(nodeCount))
                    {
                        var broadcasters      = new List <IConnection>();
                        var disconnectCounter = new DisconnectCounter();
                        loadBalancer.Configure(app =>
                        {
                            var resolver = new DefaultDependencyResolver();

                            resolver.Register(typeof(IMessageBus), () => bus);
                            resolver.Register(typeof(IConfigurationManager), () => configurationManager);
                            resolver.Register(typeof(FarmConnection), () => new FarmConnection(disconnectCounter));

                            var connectionManager = resolver.Resolve <IConnectionManager>();
                            broadcasters.Add(connectionManager.GetConnectionContext <FarmConnection>().Connection);

                            app.MapSignalR <FarmConnection>("/echo", new ConnectionConfiguration
                            {
                                Resolver = resolver
                            });
                        });

                        var transport  = new Client.Transports.LongPollingTransport(loadBalancer);
                        var connection = new Client.Connection("http://goo/echo");

                        await connection.Start(transport);

                        for (int i = 0; i < nodeCount; i++)
                        {
                            broadcasters[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)).Wait();
                            await Task.Delay(TimeSpan.FromSeconds(1));
                        }

                        ((Client.IConnection)connection).Disconnect();

                        await Task.Delay(TimeSpan.FromTicks(TimeSpan.FromSeconds(5).Ticks *nodeCount));

                        Assert.Equal(0, disconnectCounter.CleanDisconnectCount);
                        Assert.Equal(3, disconnectCounter.UncleanDisconnectCount);
                    }
        }
Example #31
0
        public async Task ContextGroupAddCompletesSuccessfully()
        {
            // https://github.com/SignalR/SignalR/issues/3337
            // Each node shares the same bus but are independent servers
            var counters             = new PerformanceCounterManager();
            var configurationManager = new DefaultConfigurationManager();

            using (EnableTracing())
                using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000))
                    using (var memoryHost = new MemoryHost())
                    {
                        memoryHost.Configure(app =>
                        {
                            var resolver = new DefaultDependencyResolver();
                            resolver.Register(typeof(IMessageBus), () => bus);
                            app.MapSignalR(new HubConfiguration {
                                Resolver = resolver
                            });
                        });

                        using (var connection = new HubConnection("http://goo/"))
                        {
                            var proxy = connection.CreateHubProxy("FarmGroupHub");

                            const string group   = "group";
                            const string message = "message";

                            var mre = new AsyncManualResetEvent();
                            proxy.On <string>("message", m =>
                            {
                                if (m == message)
                                {
                                    mre.Set();
                                }
                            });

                            await connection.Start(memoryHost);

                            // Add the connection to a group via an IHubContext on a "second" server.
                            var secondResolver = new DefaultDependencyResolver();
                            secondResolver.Register(typeof(IMessageBus), () => bus);
                            var secondConnectionManager = secondResolver.Resolve <IConnectionManager>();
                            var secondHubContext        = secondConnectionManager.GetHubContext <FarmGroupHub>();
                            await secondHubContext.Groups.Add(connection.ConnectionId, group);

                            await proxy.Invoke("SendToGroup", group, message);

                            Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(5)));
                        }
                    }
        }
Example #32
0
        public void ErrorOnSendThrowsNextTime()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);
            stream.Open();

            Task task = stream.Send(_ =>
            {
                throw new InvalidOperationException();
            },
            null);

            Assert.Throws<AggregateException>(() => task.Wait());
            Assert.Throws<InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
        public void SanitizesInstanceNames(string instanceName, string expectedSanitizedName)
        {
            // Details on how to sanitize instance names are at http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.performancecounter.instancename
            
            // Arrange
            var traceManager = new Mock<ITraceManager>();
            traceManager.Setup(tm => tm[It.IsAny<string>()]).Returns<string>(name => new TraceSource(name));

            // Act
            var perfCountersMgr = new PerformanceCounterManager(traceManager.Object);
            perfCountersMgr.Initialize(instanceName, CancellationToken.None);

            // Assert
            Assert.Equal(expectedSanitizedName, perfCountersMgr.InstanceName);
        }
Example #34
0
        public void ErrorOnSendThrowsNextTime()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", 1000, perfCounters);

            stream.Open();

            Task task = stream.Send(_ =>
            {
                throw new InvalidOperationException();
            },
                                    null);

            Assert.Throws <AggregateException>(() => task.Wait());
            Assert.Throws <InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
Example #35
0
        public void InitialToBufferingToOpenToSend()
        {
            int x            = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.SetError(new Exception());
            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(20);
                x++;
            },
                        null).Wait();

            Assert.Equal(1, x);
        }
Example #36
0
        public async Task ErrorOnSendThrowsNextTime()
        {
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();

            Task task = stream.Send(_ =>
            {
                throw new InvalidOperationException();
            },
                                    null);

            await Assert.ThrowsAsync <InvalidOperationException>(() => task);

            await Assert.ThrowsAsync <InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
        public void ErrorOnSendThrowsNextTime()
        {
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();

            Task task = stream.Send(_ =>
            {
                throw new InvalidOperationException();
            },
                                    null);

            Assert.Throws <AggregateException>(() => task.Wait());
            Assert.ThrowsAsync <InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
        public void InitialToBufferingToOpenToSend()
        {
            int x             = 0;
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.SetError(new Exception());
            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(20);
                x++;
            },
                        null).Wait();

            Assert.Equal(1, x);
        }
        public void SendThrowsNullExceptionWhenConnectionIdIsNull()
        {
            var serializer = new JsonNetSerializer();
            var counters = new PerformanceCounterManager();

            var connection = new Connection(new Mock<IMessageBus>().Object,
                                serializer,
                                "signal",
                                "connectonid",
                                new[] { "test" },
                                new string[] { },
                                new Mock<ITraceManager>().Object,
                                new AckHandler(completeAcksOnTimeout: false,
                                               ackThreshold: TimeSpan.Zero,
                                               ackInterval: TimeSpan.Zero),
                                counters,
                                new Mock<IProtectedData>().Object);

            Assert.Throws<ArgumentException>(() => connection.Send(null, new object()));
        }
        async public void SendThrowsNullExceptionWhenConnectionIdsAreNull()
        {
            var serializer = JsonUtility.CreateDefaultSerializer();
            var counters = new PerformanceCounterManager(new Mock<ILoggerFactory>().Object);

            var connection = new Connection(new Mock<IMessageBus>().Object,
                                serializer,
                                "signal",
                                "connectonid",
                                new[] { "test" },
                                new string[] { },
                                new Mock<ILoggerFactory>().Object,
                                new AckHandler(completeAcksOnTimeout: false,
                                               ackThreshold: TimeSpan.Zero,
                                               ackInterval: TimeSpan.Zero),
                                counters,
                                new Mock<IProtectedData>().Object,
                                new MemoryPool());

            await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Send((IList<string>)null, new object()));
        }
        public void SendingCommandObjectSetsCommandOnBus()
        {
            var messageBus = new Mock<IMessageBus>();
            var counters = new PerformanceCounterManager();
            Message message = null;
            messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Returns<Message>(m =>
            {
                message = m;
                return TaskAsyncHelper.Empty;
            });

            var serializer = JsonUtility.CreateDefaultSerializer();
            var traceManager = new Mock<ITraceManager>();
            var connection = new Connection(messageBus.Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "a", "signal", "connectionid" },
                                            new string[] { },
                                            traceManager.Object,
                                            new AckHandler(completeAcksOnTimeout: false,
                                                           ackThreshold: TimeSpan.Zero,
                                                           ackInterval: TimeSpan.Zero),
                                            counters,
                                            new Mock<IProtectedData>().Object,
                                            new MemoryPool());

            connection.Send("a", new Command
            {
                CommandType = CommandType.AddToGroup,
                Value = "foo"
            });

            Assert.NotNull(message);
            Assert.True(message.IsCommand);
            var command = serializer.Parse<Command>(message.Value, message.Encoding);
            Assert.Equal(CommandType.AddToGroup, command.CommandType);
            Assert.Equal("foo", command.Value);
        }
Example #42
0
        /// <summary>
        /// Installs SignalR performance counters.
        /// </summary>
        public IList <string> InstallCounters()
        {
            // Delete any existing counters
            UninstallCounters();

            var counterCreationData = SignalRPerfCounterManager.GetCounterPropertyInfo()
                                      .Select(p =>
            {
                var attribute = SignalRPerfCounterManager.GetPerformanceCounterAttribute(p);
                return(new CounterCreationData(attribute.Name, attribute.Description, attribute.CounterType));
            })
                                      .ToArray();

            var createDataCollection = new CounterCreationDataCollection(counterCreationData);

            PerformanceCounterCategory.Create(SignalRPerfCounterManager.CategoryName,
                                              "SignalR application performance counters",
                                              PerformanceCounterCategoryType.MultiInstance,
                                              createDataCollection);

            return(counterCreationData.Select(c => c.CounterName).ToList());
        }
        public void OpenQueueErrorOpenQueue()
        {
            int x             = 0;
            var loggerFactory = new Mock <ILoggerFactory>();
            var perfCounters  = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger        = new Mock <ILogger>();
            var stream        = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);

            Task t1 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                await TaskAsyncHelper.FromError(new Exception());
            },
                                  null);

            Assert.Throws <AggregateException>(() => t1.Wait());

            stream.Open();

            Task t2 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                                  null);

            t2.Wait();

            Assert.Equal(2, x);
        }
Example #44
0
        public void GroupThrowsNullExceptionWhenGroupNameIsNull()
        {
            Func<string, ClientHubInvocation, IList<string>, Task> send = (signal, value, exclude) => Task.Factory.StartNew(() => { });

            var serializer = new JsonNetSerializer();
            var counters = new PerformanceCounterManager();
            var connection = new Connection(new Mock<IMessageBus>().Object,
                    serializer,
                    "signal",
                    "connectonid",
                    new[] { "test" },
                    new string[] { },
                    new Mock<ITraceManager>().Object,
                    new AckHandler(completeAcksOnTimeout: false,
                                   ackThreshold: TimeSpan.Zero,
                                   ackInterval: TimeSpan.Zero),
                    counters,
                    new Mock<IProtectedData>().Object);

            var hubContext = new HubContext(send, "test", connection);

            Assert.Throws<ArgumentException>(() => hubContext.Clients.Group(null));
        }
Example #45
0
        public void OpenQueueErrorOpenQueue()
        {
            int x            = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream       = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);

            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                        null);

            Task t1 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                await TaskAsyncHelper.FromError(new Exception());
            },
                                  null);

            Assert.Throws <AggregateException>(() => t1.Wait());

            stream.Open();

            Task t2 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
                                  null);

            t2.Wait();

            Assert.Equal(2, x);
        }
        public void OpenQueueErrorOpenQueue()
        {
            int x = 0;
            var loggerFactory = new Mock<ILoggerFactory>();
            var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger = new Mock<ILogger>();
            var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);
            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
            null);

            Task t1 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                await TaskAsyncHelper.FromError(new Exception());
            },
            null);

            Assert.Throws<AggregateException>(() => t1.Wait());

            stream.Open();

            Task t2 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
            null);

            t2.Wait();

            Assert.Equal(2, x);
        }
 public void SendAfterCloseThenOpenRemainsClosed()
 {
     var loggerFactory = new Mock<ILoggerFactory>();
     var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
     var logger = new Mock<ILogger>();
     var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);
     stream.Open();
     stream.Send(_ => Task.Delay(50), null);
     stream.Close();
     stream.Open();
     Assert.ThrowsAsync<InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
 }
        public void SendAfterOpenAndAfterErrorThrows()
        {
            var loggerFactory = new Mock<ILoggerFactory>();
            var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger = new Mock<ILogger>();
            var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            int x = 0;

            var firstSend = stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            stream.Open();

            // Wait on the first send to drain
            firstSend.Wait();

            stream.SetError(new Exception("Failed"));

            Assert.Throws<Exception>(() =>
            {
                stream.Send(_ =>
                {
                    x++;
                    return TaskAsyncHelper.Empty;
                },
                null).Wait();
            });

            Assert.Equal(1, x);
        }
        public void SendBeforeOpenDoesNotThrowWhenQueuingBehaviorInitialOnly()
        {
            var loggerFactory = new Mock<ILoggerFactory>();
            var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger = new Mock<ILogger>();
            var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            var sendTask = stream.Send(_ => { return TaskAsyncHelper.Empty; }, null);

            stream.Open();

            // (Does not throw)
            sendTask.Wait();
        }
        public void SendsBeforeOpenedRunOnceOpenedWhenQueuingBehaviorInitialOnly()
        {
            var loggerFactory = new Mock<ILoggerFactory>();
            var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger = new Mock<ILogger>();
            var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.InitialOnly, 1000, perfCounters);

            int x = 0;

            stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            Task task = stream.Send(_ =>
            {
                x++;
                return TaskAsyncHelper.Empty;
            },
            null);

            stream.Open();

            task.Wait();

            Assert.Equal(2, x);
        }
        public void RequestCompletesAfterFaultedInitializeResponse()
        {
            // Arrange
            var response = new Mock<IResponse>();
            response.Setup(m => m.CancellationToken).Returns(CancellationToken.None);
            var request = new Mock<IRequest>();
            var qs = new NameValueCollection();
            qs["connectionId"] = "1";
            request.Setup(m => m.QueryString).Returns(new NameValueCollectionWrapper(qs));
            request.Setup(m => m.LocalPath).Returns("/test/echo/connect");
            var counters = new PerformanceCounterManager();
            var heartBeat = new Mock<ITransportHeartbeat>();
            var json = new JsonSerializer();
            var hostContext = new HostContext(request.Object, response.Object);
            var transportConnection = new Mock<ITransportConnection>();
            var traceManager = new Mock<ITraceManager>();
            traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo"));

            transportConnection.Setup(m => m.Receive(It.IsAny<string>(),
                                                     It.IsAny<Func<PersistentResponse, object, Task<bool>>>(),
                                                     It.IsAny<int>(),
                                                     It.IsAny<object>()))
                .Returns<string, Func<PersistentResponse, object, Task<bool>>, int, object>(
                    (messageId, callback, maxMessages, state) =>
                        new DisposableAction(() => callback(new PersistentResponse(), state))
                    );

            var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters, traceManager.Object)
            {
                CallBase = true
            };

            var queue = new TaskQueue();

            transport.Setup(t => t.EnqueueOperation(It.IsAny<Func<object, Task>>(), It.IsAny<object>()))
                .Returns<Func<object, Task>, object>(
                    (writeAsync, state) => queue.Enqueue(writeAsync, state));

            transport.Setup(t => t.InitializeResponse(It.IsAny<ITransportConnection>()))
                .Returns<ITransportConnection>(
                    pr => TaskAsyncHelper.FromError(new Exception()));

            transport.Setup(t => t.Send(It.IsAny<PersistentResponse>()))
                .Returns<PersistentResponse>(
                    pr => transport.Object.EnqueueOperation(() => TaskAsyncHelper.Empty));

            var tcs = new TaskCompletionSource<bool>();
            transport.Object.AfterRequestEnd = (ex) =>
            {
                // Trip the cancellation token
                tcs.TrySetResult(transport.Object.WriteQueue.IsDrained);
            };

            // Act
            transport.Object.ProcessRequest(transportConnection.Object);

            // Assert
            Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(2)));
            Assert.True(tcs.Task.Result);
        }
        public void ErrorOnSendThrowsNextTime()
        {
            var loggerFactory = new Mock<ILoggerFactory>();
            var perfCounters = new SignalRPerformanceCounterManager(loggerFactory.Object);
            var logger = new Mock<ILogger>();
            var stream = new ScaleoutStream(logger.Object, "0", QueuingBehavior.Always, 1000, perfCounters);
            stream.Open();

            Task task = stream.Send(_ =>
            {
                throw new InvalidOperationException();
            },
            null);

            Assert.Throws<AggregateException>(() => task.Wait());
            Assert.ThrowsAsync<InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
        }
        public void InitialToBufferingToOpenToSend()
        {
            int x = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);
            stream.SetError(new Exception());
            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(20);
                x++;
            },
            null).Wait();

            Assert.Equal(1, x);
        }
        public void OpenQueueErrorOpenQueue()
        {
            int x = 0;
            var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
            var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);
            stream.Open();
            stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
            null);

            Task t1 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                await TaskAsyncHelper.FromError(new Exception());
            },
            null);

            Assert.Throws<AggregateException>(() => t1.Wait());

            stream.Open();

            Task t2 = stream.Send(async _ =>
            {
                await Task.Delay(50);
                x++;
            },
            null);

            t2.Wait();

            Assert.Equal(2, x);
        }
 public void CloseWhileQueueRunsWithFailedTask()
 {
     int x = 0;
     var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
     var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);
     stream.Open();
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         x++;
     },
     null);
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         await TaskAsyncHelper.FromError(new Exception());
     },
     null);
     stream.Send(async _ =>
     {
         await Task.Delay(50);
         x++;
     },
     null);
     stream.Close();
     Assert.Equal(1, x);
 }
 public void OpenAfterClosedEnqueueThrows()
 {
     var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
     var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);
     stream.Close();
     stream.Open();
     Assert.Throws<InvalidOperationException>(() => stream.Send(_ => TaskAsyncHelper.Empty, null));
 }
Example #57
0
        public async Task FarmDisconnectRaisesUncleanDisconnects()
        {
            // Each node shares the same bus but are independent servers
            const int nodeCount            = 3;
            var       counters             = new PerformanceCounterManager();
            var       configurationManager = new DefaultConfigurationManager();

            configurationManager.DisconnectTimeout = TimeSpan.FromSeconds(6);

            using (EnableTracing())
                using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000))
                    using (var loadBalancer = new LoadBalancer(nodeCount))
                    {
                        var broadcasters      = new List <IConnection>();
                        var disconnectCounter = Channel.CreateUnbounded <DisconnectData>();
                        loadBalancer.Configure(app =>
                        {
                            var resolver = new DefaultDependencyResolver();

                            resolver.Register(typeof(IMessageBus), () => bus);
                            resolver.Register(typeof(IConfigurationManager), () => configurationManager);
                            resolver.Register(typeof(FarmConnection), () => new FarmConnection(disconnectCounter.Writer));

                            var connectionManager = resolver.Resolve <IConnectionManager>();
                            broadcasters.Add(connectionManager.GetConnectionContext <FarmConnection>().Connection);

                            app.MapSignalR <FarmConnection>("/echo", new ConnectionConfiguration
                            {
                                Resolver = resolver
                            });
                        });

                        var transport  = new Client.Transports.LongPollingTransport(loadBalancer);
                        var connection = new Client.Connection("http://goo/echo");

                        await connection.Start(transport);

                        for (int i = 0; i < nodeCount; i++)
                        {
                            broadcasters[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)).Wait();
                            await Task.Delay(TimeSpan.FromSeconds(1));
                        }

                        ((Client.IConnection)connection).Disconnect();

                        // Give up after 30 seconds
                        var cts = new CancellationTokenSource();
                        cts.CancelAfter(TimeSpan.FromSeconds(30));

                        // We can get duplicate OnDisconnected calls, and that's a known by-design issue.
                        var instancesDisconnected = new HashSet <string>();
                        while (await disconnectCounter.Reader.WaitToReadAsync(cts.Token))
                        {
                            while (!cts.IsCancellationRequested && disconnectCounter.Reader.TryRead(out var disconnect))
                            {
                                Assert.False(disconnect.StopCalled, "Disconnect should not have been due to stop being called.");
                                instancesDisconnected.Add(disconnect.InstanceName);
                                if (instancesDisconnected.Count == 3)
                                {
                                    // We're done, all three instances disconneted
                                    return;
                                }
                            }
                        }

                        // If we get here it means the cts was cancelled which means we timed out
                        cts.Token.ThrowIfCancellationRequested();
                    }
        }
        public void RequestCompletesAfterFaultedInitializeResponse()
        {
            // Arrange
            var testContext = new TestContext("/test/echo/connect");
            var counters = new PerformanceCounterManager(new Mock<ILoggerFactory>().Object);
            var heartBeat = new Mock<ITransportHeartbeat>();
            var json = new JsonSerializer();
            var transportConnection = new Mock<ITransportConnection>();
            var loggerFactory = new Mock<ILoggerFactory>();
            var memoryPool = new Mock<IMemoryPool>();
            var applicationLifetime = new Mock<IApplicationLifetime>();
            applicationLifetime.SetupGet(m => m.ApplicationStopping).Returns(CancellationToken.None);

            var logger = new Mock<ILogger>();
            loggerFactory.Setup(m => m.CreateLogger(It.IsAny<string>())).Returns(logger.Object);

            transportConnection.Setup(m => m.Receive(It.IsAny<string>(),
                                                     It.IsAny<Func<PersistentResponse, object, Task<bool>>>(),
                                                     It.IsAny<int>(),
                                                     It.IsAny<object>()))
                .Returns<string, Func<PersistentResponse, object, Task<bool>>, int, object>(
                    (messageId, callback, maxMessages, state) =>
                        new DisposableAction(() => callback(new PersistentResponse(), state))
                    );

            var transport = new Mock<ForeverTransport>(testContext.MockHttpContext.Object, json, heartBeat.Object, counters, applicationLifetime.Object, loggerFactory.Object, memoryPool.Object)
            {
                CallBase = true
            };

            var queue = new TaskQueue();

            transport.Setup(t => t.EnqueueOperation(It.IsAny<Func<object, Task>>(), It.IsAny<object>()))
                .Returns<Func<object, Task>, object>(
                    (writeAsync, state) => queue.Enqueue(writeAsync, state));

            transport.Setup(t => t.InitializeResponse(It.IsAny<ITransportConnection>()))
                .Returns<ITransportConnection>(
                    pr => TaskAsyncHelper.FromError(new Exception()));

            transport.Setup(t => t.Send(It.IsAny<PersistentResponse>()))
                .Returns<PersistentResponse>(
                    pr => transport.Object.EnqueueOperation(() => TaskAsyncHelper.Empty));

            var tcs = new TaskCompletionSource<bool>();
            transport.Object.AfterRequestEnd = (ex) =>
            {
                // Trip the cancellation token
                tcs.TrySetResult(transport.Object.WriteQueue.IsDrained);
            };

            // Act
            transport.Object.ProcessRequest(transportConnection.Object);

            // Assert
            Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(2)));
            Assert.True(tcs.Task.Result);
        }
 public void InitialToClosed()
 {
     var perfCounters = new Microsoft.AspNet.SignalR.Infrastructure.PerformanceCounterManager();
     var stream = new ScaleoutStream(new TraceSource("Queue"), "0", QueuingBehavior.Always, 1000, perfCounters);
     stream.Close();
 }
        public void AcksAreSentToAckSubscriber()
        {
            // Arrange
            var waitCommand = new Command { WaitForAck = true };
            var ackerId = "acker";
            var waiterId = "waiter";
            var messageId = "messageId";
            var maxMessages = 1;

            var ackHandler = new Mock<IAckHandler>();
            ackHandler.Setup(m => m.TriggerAck(waitCommand.Id)).Returns(false);

            var messageBus = new Mock<IMessageBus>();
            Message waitMessage = null;
            Message ackMessage = null;
            messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Returns<Message>(m =>
            {
                if (m.WaitForAck)
                {
                    waitMessage = m;
                }
                else if (m.IsAck)
                {
                    ackMessage = m;
                }

                return TaskAsyncHelper.Empty;
            });

            var loggerFactory = new Mock<ILoggerFactory>();
            var counters = new PerformanceCounterManager(loggerFactory.Object);

            var serializer = JsonUtility.CreateDefaultSerializer();
            var waiterConnection = new Connection(messageBus.Object,
                                                  serializer,
                                                  "signal",
                                                  waiterId,
                                                  new string[] { },
                                                  new string[] { },
                                                  loggerFactory.Object,
                                                  ackHandler.Object,
                                                  counters,
                                                  new Mock<IProtectedData>().Object,
                                                  new MemoryPool());

            // Act
            waiterConnection.Send(ackerId, waitCommand);

            // Assert
            Assert.NotNull(waitMessage);
            Assert.Equal(waiterId, waitMessage.Source);
            Assert.Equal(PrefixHelper.GetConnectionId(ackerId), waitMessage.Key);

            // Arrange some more now that we have a waitMessage
            var messages = new List<ArraySegment<Message>>()
            {
                new ArraySegment<Message>(new[] { waitMessage })
            };
            var messageResult = new MessageResult(messages, 1);

            var ackerConnection = new Connection(messageBus.Object,
                                                 serializer,
                                                 "signal",
                                                 ackerId,
                                                 new string[] { },
                                                 new string[] { },
                                                 loggerFactory.Object,
                                                 ackHandler.Object,
                                                 counters,
                                                 new Mock<IProtectedData>().Object,
                                                 new Mock<IMemoryPool>().Object);
            ackerConnection.WriteCursor = _ => { };

            messageBus.Setup(m => m.Subscribe(ackerConnection,
                                              messageId,
                                              It.IsAny<Func<MessageResult, object, Task<bool>>>(),
                                              maxMessages,
                                              It.IsAny<object>()))
                .Callback<ISubscriber,
                          string,
                          Func<MessageResult, object, Task<bool>>,
                          int,
                          object>((subsciber, cursor, callback, max, state) =>
                {
                    callback(messageResult, state);
                });

            // Act
            ackerConnection.Receive(messageId, (_, __) => TaskAsyncHelper.False, maxMessages, null);

            // Assert
            Assert.NotNull(ackMessage);
            Assert.Equal(ackerId, ackMessage.Source);
            Assert.Equal(AckSubscriber.Signal, ackMessage.Key);
        }