コード例 #1
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();
                    }
                }
            }
        }
コード例 #2
0
        public void EnsureHubThrowsWhenCantResolve()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var hubManager = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);

            Assert.Throws <InvalidOperationException>(() => hubManager.EnsureHub("__ELLO__"));
        }
コード例 #3
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.AddSingleton <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);
            }
コード例 #4
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.AddSingleton <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);
            }
コード例 #5
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);
            }
        }
コード例 #6
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();
                    }
                }
            }
        }
コード例 #7
0
        public void SubscriptionWithCancelledTaskCanBeDisposed()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

            using (var bus = (MessageBus)sp.GetRequiredService <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();
            }
        }
コード例 #8
0
        public void MessageBusCanBeDisposedTwiceWithoutHanging()
        {
            var bus = (IDisposable)ServiceProviderHelper.CreateServiceProvider().GetRequiredService <IMessageBus>();

            bus.Dispose();
            Assert.True(Task.Run(() => bus.Dispose()).Wait(TimeSpan.FromSeconds(10)));
        }
コード例 #9
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.AddSingleton <IProtectedData>(protectedData.Object);
                });

                connection.Object.Initialize(sp);

                return(connection.Object.VerifyGroups(connectionId, groupsToken));
            }
コード例 #10
0
        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.Features.Get <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());
        }
コード例 #11
0
        public void GetInValidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var hubManager    = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.GetHub("__ELLO__");

            Assert.Null(hubDescriptor);
        }
コード例 #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 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");
        }
コード例 #14
0
        public void ResolveHubsIsNotEmpty()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var hubManager    = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.ResolveHubs();

            Assert.NotNull(hubDescriptor);
            Assert.NotEmpty(hubDescriptor);
        }
コード例 #15
0
        public void GetValidHubMethodsWithPredicate()
        {
            var sp                = ServiceProviderHelper.CreateServiceProvider();
            var hubManager        = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var methodDescriptors = hubManager.GetHubMethods(nameof(CoreTestHubWithMethod), descriptor => descriptor.Name == "AddNumbers");

            Assert.NotNull(methodDescriptors);
            Assert.Equal(methodDescriptors.First().Name, "AddNumbers");
        }
コード例 #16
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);
        }
コード例 #17
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);
        }
コード例 #18
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(nameof(CoreTestHubWithMethod), "AddNumbers", null);

            Assert.Null(methodDescriptor);
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        public void ShouldNotResolveHubByTypeNameIfAttributeExists()
        {
            var           sp          = ServiceProviderHelper.CreateServiceProvider();
            var           hubResolver = ActivatorUtilities.CreateInstance <ReflectedHubDescriptorProvider>(sp);
            HubDescriptor hub;

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

            Assert.Null(hub);
        }
コード例 #21
0
        public void GetValidHubMethodsWithInvalidPredicate()
        {
            var sp                = ServiceProviderHelper.CreateServiceProvider();
            var hubManager        = ActivatorUtilities.CreateInstance <DefaultHubManager>(sp);
            var methodDescriptors = hubManager.GetHubMethods(nameof(CoreTestHubWithMethod), descriptor => descriptor.Name == "______AddNumbers______");

            // Still have an ienumerable sequence
            Assert.NotNull(methodDescriptors);
            // But there's nothing in the ienumerable
            Assert.Empty(methodDescriptors);
        }
コード例 #22
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);
        }
コード例 #23
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"));
            }
        }
コード例 #24
0
        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);
        }
コード例 #25
0
        public void NewSubscriptionGetsAllMessages()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

            using (var bus = ActivatorUtilities.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();
                    }
                }
            }
        }
コード例 #26
0
        public void SubscriptionPullFromMultipleStreamsInFairOrder()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

            using (var bus = ActivatorUtilities.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();
                    }
                }
            }
        }
コード例 #27
0
        public void SubscriptionGetsCorrectCursorsIfLessKeysThanStreams()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

            using (var bus = ActivatorUtilities.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();
                    }
                }
            }
        }
コード例 #28
0
        public void ForeverFrameTransportEscapesTags(string data, string expected)
        {
            var context = new TestContext("/");
            var sp      = ServiceProviderHelper.CreateServiceProvider();

            var ms = new MemoryStream();

            context.MockResponse.Setup(m => m.Body).Returns(ms);

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

            AssertEscaped(fft, ms, data, expected);
        }
コード例 #29
0
        public void SubscriptionWithExistingCursor()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider();

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

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

                bus.Publish(1, 0, new[] {
                    new Message("test1", "key", "51")
                });

                bus.Publish(1, 2, new[] {
                    new Message("test2", "key", "2"),
                    new Message("test3", "key", "3"),
                    new Message("test2", "key", "4"),
                });

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

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

                    bus.Publish(0, 2, new[] { new Message("test", "key", "5") });

                    Assert.True(cd.Wait(TimeSpan.FromSeconds(10)));
                }
                finally
                {
                    if (subscription != null)
                    {
                        subscription.Dispose();
                    }
                }
            }
        }
コード例 #30
0
        public void SubscriptionWithExistingCursor()
        {
            var sp = ServiceProviderHelper.CreateServiceProvider(services =>
            {
                var passThroughMinfier = new PassThroughStringMinifier();
                services.AddSingleton <IStringMinifier>(passThroughMinfier);
            });

            using (var bus = (MessageBus)sp.GetRequiredService <IMessageBus>())
            {
                Func <TestSubscriber> subscriberFactory = () => new TestSubscriber(new[] { "key" });
                var         cd           = new CountDownRange <int>(Enumerable.Range(2, 4));
                IDisposable subscription = null;
                string      prefix       = DefaultSubscription._defaultCursorPrefix;

                // Pretend like we had an initial subscription
                bus.Subscribe(subscriberFactory(), null, (result, state) => TaskAsyncHelper.True, 10, null)
                .Dispose();

                bus.Publish("test", "key", "1").Wait();
                bus.Publish("test", "key", "2").Wait();
                bus.Publish("test", "key", "3").Wait();
                bus.Publish("test", "key", "4").Wait();

                try
                {
                    subscription = bus.Subscribe(subscriberFactory(), prefix + "key,00000001", (result, state) =>
                    {
                        foreach (var m in result.GetMessages())
                        {
                            int n = Int32.Parse(m.GetString());
                            Assert.True(cd.Mark(n));
                        }

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

                    bus.Publish("test", "key", "5");

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