예제 #1
0
        public void MessageBusCanBeDisposedTwiceWithoutHanging()
        {
            var bus = (IDisposable)ServiceProviderHelper.CreateServiceProvider().GetRequiredService <IMessageBus>();

            bus.Dispose();
            Assert.True(Task.Run(() => bus.Dispose()).Wait(TimeSpan.FromSeconds(10)));
        }
예제 #2
0
            public void AuthenticatedUserWithColonsInUserName()
            {
                var connection = new Mock <PersistentConnection>()
                {
                    CallBase = true
                };
                var context = new TestContext("/");

                context.MockHttpContext.Setup(m => m.User)
                .Returns(new ClaimsPrincipal(new GenericIdentity("::11:::::::1:1")));

                string connectionId = Guid.NewGuid().ToString("d");

                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);

                var sp = ServiceProviderHelper.CreateServiceProvider(services =>
                {
                    services.AddInstance <IProtectedData>(protectedData.Object);
                });

                connection.Object.Initialize(sp);

                string cid;
                string message;
                int    statusCode;

                Assert.Equal(true, connection.Object.TryGetConnectionId(context.MockHttpContext.Object, connectionId + ":::11:::::::1:1", out cid, out message, out statusCode));
                Assert.Equal(connectionId, cid);
            }
        public void EnsureHubThrowsWhenCantResolve()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var hubManager = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);

            Assert.Throws <InvalidOperationException>(() => hubManager.EnsureHub("__ELLO__"));
        }
예제 #4
0
        public void GetTopicDoesNotChangeStateWhenNotDying()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider(services =>
            {
                services.SetupOptions <SignalROptions>(options =>
                {
                    options.Transports.DisconnectTimeout = TimeSpan.FromSeconds(6);
                    options.Transports.KeepAlive         = null;
                });
            });

            using (var bus = (MessageBus)sp.GetService <IMessageBus>())
            {
                bus.Subscribe(new TestSubscriber(new[] { "key" }), null, (result, state) => TaskAsyncHelper.True, 10, null);
                Topic topic;
                Assert.True(bus.Topics.TryGetValue("key", out topic));
                Assert.Equal(TopicState.HasSubscriptions, topic.State);
                topic = bus.GetTopic("key");
                Assert.Equal(TopicState.HasSubscriptions, topic.State);
                topic.RemoveSubscription(topic.Subscriptions.First());
                Assert.Equal(TopicState.NoSubscriptions, topic.State);
                topic = bus.GetTopic("key");
                Assert.Equal(TopicState.NoSubscriptions, topic.State);
                topic.State = TopicState.Dying;
                topic       = bus.GetTopic("key");
                Assert.Equal(TopicState.NoSubscriptions, topic.State);
            }
        }
예제 #5
0
        public void GarbageCollectingTopicsAfterGettingTopicsNoops()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

            using (var bus = (MessageBus)sp.GetRequiredService <IMessageBus>())
            {
                var         subscriber   = new TestSubscriber(new[] { "key" });
                IDisposable subscription = null;
                bus.AfterTopicMarkedSuccessfully = (key, topic) =>
                {
                    bus.GarbageCollectTopics();
                };

                try
                {
                    subscription = bus.Subscribe(subscriber, null, (result, state) => TaskAsyncHelper.True, 10, null);

                    Assert.Equal(1, bus.Topics.Count);
                    Topic topic;
                    Assert.True(bus.Topics.TryGetValue("key", out topic));
                    Assert.Equal(TopicState.HasSubscriptions, topic.State);
                }
                finally
                {
                    if (subscription != null)
                    {
                        subscription.Dispose();
                    }
                }
            }
        }
        public void ForeverFrameTransportDisablesRequestBuffering()
        {
            var qs = new Dictionary <string, string> {
                { "frameId", "1" }
            };
            var context = new TestContext("/", qs);
            var sp      = ServiceProviderHelper.CreateServiceProvider();

            var ms        = new MemoryStream();
            var buffering = new Mock <IHttpBufferingFeature>();

            context.MockHttpContext.Setup(m => m.GetFeature <IHttpBufferingFeature>())
            .Returns(buffering.Object);
            context.MockResponse.SetupAllProperties();
            context.MockResponse.Setup(m => m.Body).Returns(ms);

            var fft = ActivatorUtilities.CreateInstance <ForeverFrameTransport>(sp, context.MockHttpContext.Object);

            fft.ConnectionId = "1";
            var connection = new Mock <ITransportConnection>();

            fft.InitializeResponse(connection.Object).Wait();

            buffering.Verify(m => m.DisableRequestBuffering(), Times.Once());
        }
예제 #7
0
            public void UnauthenticatedUserWithAuthenticatedTokenFails()
            {
                var connection = new Mock <PersistentConnection>()
                {
                    CallBase = true
                };
                var context = new TestContext("/");

                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);

                var sp = ServiceProviderHelper.CreateServiceProvider(services =>
                {
                    services.AddInstance <IProtectedData>(protectedData.Object);
                });

                connection.Object.Initialize(sp);

                string connectionId;
                string message;
                int    statusCode;

                Assert.Equal(false, connection.Object.TryGetConnectionId(context.MockHttpContext.Object, "1:::11:::::::1:1", out connectionId, out message, out statusCode));
                Assert.Equal(403, statusCode);
            }
예제 #8
0
        public void GetTopicDoesNotChangeStateWhenNotDying()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider(services =>
            {
                services.Configure <MessageBusOptions>(options =>
                {
                    options.TopicTTL = TopicTtl(TimeSpan.FromSeconds(6));
                });
            });

            using (var bus = (MessageBus)sp.GetRequiredService <IMessageBus>())
            {
                bus.Subscribe(new TestSubscriber(new[] { "key" }), null, (result, state) => TaskAsyncHelper.True, 10, null);
                Topic topic;
                Assert.True(bus.Topics.TryGetValue("key", out topic));
                Assert.Equal(TopicState.HasSubscriptions, topic.State);
                topic = bus.GetTopic("key");
                Assert.Equal(TopicState.HasSubscriptions, topic.State);
                topic.RemoveSubscription(topic.Subscriptions.First());
                Assert.Equal(TopicState.NoSubscriptions, topic.State);
                topic = bus.GetTopic("key");
                Assert.Equal(TopicState.NoSubscriptions, topic.State);
                topic.State = TopicState.Dying;
                topic       = bus.GetTopic("key");
                Assert.Equal(TopicState.NoSubscriptions, topic.State);
            }
        }
예제 #9
0
        public void SubscriptionWithCancelledTaskCanBeDisposed()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

            using (var bus = (MessageBus)sp.GetService <IMessageBus>())
            {
                var subscriber = new TestSubscriber(new[] { "key" });
                var wh         = new ManualResetEventSlim();

                IDisposable subscription = bus.Subscribe(subscriber, null, async(result, state) =>
                {
                    if (result.Terminal)
                    {
                        return(false);
                    }

                    await Task.Delay(50);
                    var tcs = new TaskCompletionSource <bool>();
                    tcs.SetCanceled();
                    wh.Set();
                    return(await tcs.Task);
                }, 10, null);

                bus.Publish("me", "key", "hello");

                wh.Wait();

                subscription.Dispose();
            }
        }
예제 #10
0
            private static IList <string> DoVerifyGroups(string groupsToken, string connectionId, bool hasProtectedData = true)
            {
                var connection = new Mock <PersistentConnection>()
                {
                    CallBase = true
                };
                var qs      = new Dictionary <string, string>();
                var context = new TestContext("/", qs);

                context.MockResponse.SetupProperty(r => r.StatusCode);
                qs["transport"]       = "serverSentEvents";
                qs["connectionToken"] = "1";
                qs["groupsToken"]     = groupsToken;

                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) => hasProtectedData ? value : null);

                var sp = ServiceProviderHelper.CreateServiceProvider(services =>
                {
                    services.AddInstance <IProtectedData>(protectedData.Object);
                });

                connection.Object.Initialize(sp);

                return(connection.Object.VerifyGroups(connectionId, groupsToken));
            }
예제 #11
0
        public void SubscriptionDoesNotGetNewMessagesWhenTopicStoreOverrunByOtherStream()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider(services =>
            {
                services.Configure <MessageBusOptions>(options =>
                {
                    options.MessageBufferSize = 10;
                });
            });

            using (var bus = ActivatorUtilities.CreateInstance <TestScaleoutBus>(sp, 2))
            {
                var         subscriber   = new TestSubscriber(new[] { "key" });
                IDisposable subscription = null;

                // The min fragment size is 8 and min fragments is 5
                var expectedValues = Enumerable.Range(171, 8);
                var cd             = new OrderedCountDownRange <int>(expectedValues);

                // This will overwrite the buffer ending up with (40 - 79) for stream 2
                for (int i = 0; i < 80; i++)
                {
                    bus.Publish(0, (ulong)i, new[] {
                        new Message("test", "key", i.ToString())
                    });
                }

                // This will overwrite the buffer with (140 - 179) for stream 1
                for (int i = 100; i < 180; i++)
                {
                    bus.Publish(1, (ulong)i, new[] {
                        new Message("test", "key", i.ToString())
                    });
                }

                try
                {
                    subscription = bus.Subscribe(subscriber, "s-0,27|1,AA", (result, state) =>
                    {
                        foreach (var m in result.GetMessages())
                        {
                            int n = Int32.Parse(m.GetString());

                            cd.Expect(n);
                        }

                        return(TaskAsyncHelper.True);
                    }, 100, null);

                    Assert.True(cd.Wait(TimeSpan.FromSeconds(10)));
                }
                finally
                {
                    if (subscription != null)
                    {
                        subscription.Dispose();
                    }
                }
            }
        }
예제 #12
0
        public void ResolveInvalidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var hubManager    = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.ResolveHub("____CoreTestHub____");

            Assert.Null(hubDescriptor);
        }
예제 #13
0
        public void GetInValidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var hubManager    = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.GetHub("__ELLO__");

            Assert.Null(hubDescriptor);
        }
예제 #14
0
        public void GetValidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var hubManager    = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.GetHub("CoreTestHub");

            Assert.NotNull(hubDescriptor);
            Assert.False(hubDescriptor.NameSpecified);
        }
예제 #15
0
        public void GetHubMethodFromInvalidHub()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var hubManager = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            // There is no ________________CoreTestHubWithMethod________________ name
            var methodDescriptor = hubManager.GetHubMethod("________________CoreTestHubWithMethod________________", "AddNumbers", new IJsonValue[] { null, null });

            Assert.Null(methodDescriptor);
        }
        public void ResolveValidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var ta            = new TypeActivator();
            var hubManager    = ta.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.ResolveHub("CoreTestHub");

            Assert.NotNull(hubDescriptor);
        }
예제 #17
0
        public void ResolveHubsIsNotEmpty()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var hubManager    = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.ResolveHubs();

            Assert.NotNull(hubDescriptor);
            Assert.NotEmpty(hubDescriptor);
        }
예제 #18
0
        public void GetValidHubsWithValidPredicate()
        {
            var sp             = ServiceProviderHelper.CreateServiceProvider();
            var hubManager     = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptors = hubManager.GetHubs(descriptor => descriptor.Name == "CoreTestHub");

            Assert.NotNull(hubDescriptors);
            Assert.Equal(hubDescriptors.First().Name, "CoreTestHub");
        }
예제 #19
0
        public void GetInvalidHubMethod()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var hubManager = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            // The AddNumbers method has 2 parameters, so should not find the method
            var methodDescriptor = hubManager.GetHubMethod("CoreTestHubWithMethod", "AddNumbers", null);

            Assert.Null(methodDescriptor);
        }
예제 #20
0
        public void GetValidHubMethodsWithPredicate()
        {
            var sp                = ServiceProviderHelper.CreateServiceProvider();
            var hubManager        = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var methodDescriptors = hubManager.GetHubMethods("CoreTestHubWithMethod", descriptor => descriptor.Name == "AddNumbers");

            Assert.NotNull(methodDescriptors);
            Assert.Equal(methodDescriptors.First().Name, "AddNumbers");
        }
        public void ShouldIgnoreCaseWhenDiscoveringHubsUsingManager()
        {
            var sp      = ServiceProviderHelper.CreateServiceProvider();
            var manager = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hub     = manager.GetHub("hubwithoutattribute");

            Assert.NotNull(hub);
            Assert.Equal(hub.Name, "HubWithoutAttribute");
            Assert.Equal(hub.NameSpecified, false);
        }
        public void ShouldNotResolveHubByTypeNameIfAttributeExists()
        {
            var           sp          = ServiceProviderHelper.CreateServiceProvider();
            var           hubResolver = ActivatorUtilities.CreateInstance <ReflectedHubDescriptorProvider>(sp);
            HubDescriptor hub;

            hubResolver.TryGetHub("HubWithAttribute", out hub);

            Assert.Null(hub);
        }
예제 #23
0
        public void GetValidHubsWithInvalidPredicate()
        {
            var sp             = ServiceProviderHelper.CreateServiceProvider();
            var hubManager     = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptors = hubManager.GetHubs(descriptor => descriptor.Name == "CoreTestHub_INVALIDHUB_____");

            // Still have an ienumerable sequence
            Assert.NotNull(hubDescriptors);
            // But there's nothing in the ienumerable
            Assert.Empty(hubDescriptors);
        }
예제 #24
0
        public void ShouldNotResolveHubByFullTypeName()
        {
            var           sp          = ServiceProviderHelper.CreateServiceProvider();
            var           ta          = new TypeActivator();
            var           hubResolver = ta.CreateInstance <ReflectedHubDescriptorProvider>(sp);
            HubDescriptor hub;

            hubResolver.TryGetHub("SignalR.Tests.HubWithoutAttribute", out hub);

            Assert.Null(hub);
        }
예제 #25
0
        public void GetValidHubMethodsWithInvalidPredicate()
        {
            var sp                = ServiceProviderHelper.CreateServiceProvider();
            var hubManager        = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var methodDescriptors = hubManager.GetHubMethods("CoreTestHubWithMethod", descriptor => descriptor.Name == "______AddNumbers______");

            // Still have an ienumerable sequence
            Assert.NotNull(methodDescriptors);
            // But there's nothing in the ienumerable
            Assert.Empty(methodDescriptors);
        }
예제 #26
0
        public void PublishingDoesNotCreateTopic()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

            using (var bus = (MessageBus)sp.GetRequiredService <IMessageBus>())
            {
                bus.Publish("test", "key", "1").Wait();

                Assert.Equal(0, bus.Topics.Count);
                Assert.False(bus.Topics.ContainsKey("key"));
            }
        }
        public void ShouldResolveHubByTypeName()
        {
            var           sp          = ServiceProviderHelper.CreateServiceProvider();
            var           hubResolver = ActivatorUtilities.CreateInstance <ReflectedHubDescriptorProvider>(sp);
            HubDescriptor hub;

            hubResolver.TryGetHub("HubWithoutAttribute", out hub);

            Assert.NotNull(hub);
            Assert.Equal(hub.Name, "HubWithoutAttribute");
            Assert.Equal(hub.NameSpecified, false);
        }
        public void SubscriptionPullFromMultipleStreamsInFairOrder()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();
            var ta = new TypeActivator();

            using (var bus = ta.CreateInstance <TestScaleoutBus>(sp, 3))
            {
                var         subscriber   = new TestSubscriber(new[] { "key" });
                var         cd           = new OrderedCountDownRange <int>(new[] { 1, 2, 4, 3 });
                IDisposable subscription = null;

                bus.Publish(0, 1, new[] {
                    new Message("test", "key", "3"),
                    new Message("test", "key2", "5"),
                },
                            new DateTime(TimeSpan.TicksPerDay * 5, DateTimeKind.Local));

                bus.Publish(1, 1, new[] {
                    new Message("test", "key", "1"),
                    new Message("test", "key2", "foo")
                },
                            new DateTime(TimeSpan.TicksPerDay * 1, DateTimeKind.Local));

                bus.Publish(2, 1, new[] {
                    new Message("test", "key", "2"),
                    new Message("test", "key", "4")
                },
                            new DateTime(TimeSpan.TicksPerDay * 2, DateTimeKind.Local));

                try
                {
                    subscription = bus.Subscribe(subscriber, "s-0,0|1,0|2,0", (result, state) =>
                    {
                        foreach (var m in result.GetMessages())
                        {
                            int n = Int32.Parse(m.GetString());
                            Assert.True(cd.Expect(n));
                        }

                        return(TaskAsyncHelper.True);
                    }, 10, null);

                    Assert.True(cd.Wait(TimeSpan.FromSeconds(10)));
                }
                finally
                {
                    if (subscription != null)
                    {
                        subscription.Dispose();
                    }
                }
            }
        }
        public void NewSubscriptionGetsAllMessages()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();
            var ta = new TypeActivator();

            using (var bus = ta.CreateInstance <TestScaleoutBus>(sp))
            {
                var         subscriber   = new TestSubscriber(new[] { "key" });
                var         wh           = new ManualResetEventSlim(initialState: false);
                IDisposable subscription = null;

                try
                {
                    var firstMessages = new[] { new Message("test1", "key", "1"),
                                                new Message("test2", "key", "2") };

                    bus.Publish(0, 0, firstMessages);

                    subscription = bus.Subscribe(subscriber, null, (result, state) =>
                    {
                        if (!result.Terminal)
                        {
                            var ms = result.GetMessages().ToList();

                            Assert.Equal(2, ms.Count);
                            Assert.Equal("key", ms[0].Key);
                            Assert.Equal("x", ms[0].GetString());
                            Assert.Equal("key", ms[1].Key);
                            Assert.Equal("y", ms[1].GetString());

                            wh.Set();

                            return(TaskAsyncHelper.True);
                        }

                        return(TaskAsyncHelper.False);
                    }, 10, null);

                    var messages = new[] { new Message("test1", "key", "x"),
                                           new Message("test1", "key", "y") };
                    bus.Publish(0, 1, messages);

                    Assert.True(wh.Wait(TimeSpan.FromSeconds(10)));
                }
                finally
                {
                    if (subscription != null)
                    {
                        subscription.Dispose();
                    }
                }
            }
        }
        public void SubscriptionGetsCorrectCursorsIfLessKeysThanStreams()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();
            var ta = new TypeActivator();

            using (var bus = ta.CreateInstance <TestScaleoutBus>(sp, 2))
            {
                var         subscriber   = new TestSubscriber(new[] { "key" });
                IDisposable subscription = null;
                var         cd           = new OrderedCountDownRange <int>(new[] { 101, 11 });

                bus.Publish(0, 10ul, new[] {
                    new Message("test", "key", "100")
                });

                bus.Publish(1, 10ul, new[] {
                    new Message("test", "key", "10")
                });

                try
                {
                    subscription = bus.Subscribe(subscriber, "s-0,0", (result, state) =>
                    {
                        foreach (var m in result.GetMessages())
                        {
                            int n = Int32.Parse(m.GetString());
                            cd.Expect(n);
                        }

                        return(TaskAsyncHelper.True);
                    }, 100, null);

                    bus.Publish(0, 11ul, new[] {
                        new Message("test", "key", "101")
                    },
                                new DateTime(TimeSpan.TicksPerDay * 1));

                    bus.Publish(1, 11ul, new[] {
                        new Message("test", "key", "11")
                    },
                                new DateTime(TimeSpan.TicksPerDay * 2));

                    Assert.True(cd.Wait(TimeSpan.FromSeconds(10)));
                }
                finally
                {
                    if (subscription != null)
                    {
                        subscription.Dispose();
                    }
                }
            }
        }