public async Task Publish_MessageStreamProvidePlusBehavior_MessagesReceived()
        {
            var receivedStreams = 0;
            var receivedEvents  = 0;

            var testBehavior    = new TestBehavior();
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AddDelegateSubscriber(
                    (IMessageStreamEnumerable <IEvent> enumerable) =>
            {
                Interlocked.Increment(ref receivedStreams);
                foreach (var dummy in enumerable)
                {
                    Interlocked.Increment(ref receivedEvents);
                }
            })
                .AddSingletonBehavior(testBehavior));
            var streamPublisher = serviceProvider.GetRequiredService <IStreamPublisher>();

            var streamProvider = new MessageStreamProvider <IEvent>();

            await streamPublisher.PublishAsync(streamProvider);

            await streamProvider.PushAsync(new TestEventOne());

            await streamProvider.PushAsync(new TestEventTwo());

            await AsyncTestingUtil.WaitAsync(() => receivedEvents >= 2);

            receivedStreams.Should().Be(1);
            receivedEvents.Should().Be(2);
        }
Ejemplo n.º 2
0
        public async Task ConnectAsync_WithEndpointConfigurators_InvokedOnce()
        {
            var configurator1 = Substitute.For <IEndpointsConfigurator>();
            var configurator2 = Substitute.For <IEndpointsConfigurator>();

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .AddBroker <TestOtherBroker>())
                .AddEndpointsConfigurator(_ => configurator1)
                .AddEndpointsConfigurator(_ => configurator2));

            var broker      = serviceProvider.GetRequiredService <TestBroker>();
            var otherBroker = serviceProvider.GetRequiredService <TestOtherBroker>();

            await broker.ConnectAsync();

            await otherBroker.ConnectAsync();

            await broker.ConnectAsync();

            await otherBroker.ConnectAsync();

            configurator1.Received(1).Configure(Arg.Any <IEndpointsConfigurationBuilder>());
            configurator2.Received(1).Configure(Arg.Any <IEndpointsConfigurationBuilder>());
        }
Ejemplo n.º 3
0
        public async Task InvokeAsync_NoMatchingHandler_TypesResolvedOnlyOnce()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(options => options.AddBroker <TestBroker>()));

            var substituteServiceProvider = Substitute.For <IServiceProvider>();

            substituteServiceProvider
            .GetService(typeof(IEnumerable <IBrokerCallback>))
            .Returns(Array.Empty <IBrokerCallback>());

            var invoker = serviceProvider.GetRequiredService <IBrokerCallbacksInvoker>();

            await invoker.InvokeAsync <ICallbackOneHandlerAsync>(
                handler => handler.HandleAsync(),
                substituteServiceProvider);

            await invoker.InvokeAsync <ICallbackTwoHandlerAsync>(
                handler => handler.HandleAsync(),
                substituteServiceProvider);

            await invoker.InvokeAsync <ICallbackOneHandlerAsync>(
                handler => handler.HandleAsync(),
                substituteServiceProvider);

            substituteServiceProvider.ReceivedWithAnyArgs(1).GetService(null !);
        }
        public async Task AddInbound_WithMessageTypeParameter_TypedDefaultSerializerSet()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(broker => broker.AddKafka())
                .AddKafkaEndpoints(
                    endpoints => endpoints
                    .Configure(
                        config =>
            {
                config.BootstrapServers = "PLAINTEXT://unittest";
            })
                    .AddInbound(
                        typeof(TestEventOne),
                        endpoint => endpoint
                        .Configure(
                            config =>
            {
                config.GroupId = "group";
            })
                        .ConsumeFrom("test"))));

            var broker = serviceProvider.GetRequiredService <KafkaBroker>();

            await broker.ConnectAsync();

            broker.Consumers[0].Endpoint.Serializer.Should().BeOfType <JsonMessageSerializer <TestEventOne> >();
        }
Ejemplo n.º 5
0
        public async Task StartAsync_ExceptionWithRetryEnabled_ConnectRetried()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddTransient(_ => Substitute.For <IApplicationLifetime>())
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .AddBroker <TestOtherBroker>()
                    .WithConnectionOptions(
                        new BrokerConnectionOptions
            {
                Mode           = BrokerConnectionMode.Startup,
                RetryOnFailure = true,
                RetryInterval  = TimeSpan.FromMilliseconds(1)
            })));

            var testBroker = serviceProvider.GetRequiredService <TestBroker>();

            testBroker.SimulateConnectIssues = true;

            var service = serviceProvider.GetServices <IHostedService>().OfType <BrokerConnectorService>().Single();
            await service.StartAsync(CancellationToken.None);

            var brokers = serviceProvider.GetRequiredService <IBrokerCollection>();

            brokers.ForEach(broker => broker.IsConnected.Should().BeTrue());

            testBroker.SimulateConnectIssues.Should().BeFalse(); // Check that the exception mechanism what triggered
        }
Ejemplo n.º 6
0
        public async Task Publish_SimpleMessageAndObservableOfMessages_StreamSubscribersNotInvoked()
        {
            var receivedStreams = 0;

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AsObservable()
                .AddDelegateSubscriber(
                    (IMessageStreamObservable <IEvent> observable) =>
            {
                Interlocked.Increment(ref receivedStreams);
                observable.Subscribe(_ => { });
            })
                .AddDelegateSubscriber(
                    (IMessageStreamObservable <TestEventOne> observable) =>
            {
                Interlocked.Increment(ref receivedStreams);
                observable.Subscribe(_ => { });
            }));
            var publisher = serviceProvider.GetRequiredService <IPublisher>();

            publisher.Publish(new TestEventOne());
            await publisher.PublishAsync(new TestEventTwo());

            await Task.Delay(200);

            receivedStreams.Should().Be(0);
        }
        public async Task CheckHealthAsync_ConsumerNotReady_UnhealthyReturned()
        {
            var statusInfo = Substitute.For <IConsumerStatusInfo>();

            statusInfo.Status.Returns(ConsumerStatus.Connected);
            var consumer = Substitute.For <IConsumer>();

            consumer.StatusInfo.Returns(statusInfo);
            consumer.Id.Returns(new InstanceIdentifier(Guid.Empty));
            consumer.Endpoint.Returns(new TestConsumerEndpoint("topic1"));
            var broker = Substitute.For <IBroker>();

            broker.ProducerEndpointType.Returns(typeof(TestProducerEndpoint));
            broker.ConsumerEndpointType.Returns(typeof(TestConsumerEndpoint));
            broker.Consumers.Returns(new[] { consumer });

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddSilverback()
                .Services
                .AddSingleton <IBrokerCollection>(new BrokerCollection(new[] { broker }))
                .AddHealthChecks()
                .AddConsumersCheck());

            var(healthCheck, context) = GetHealthCheck(serviceProvider);

            var result = await healthCheck.CheckHealthAsync(context);

            result.Status.Should().Be(HealthStatus.Unhealthy);
            result.Description.Should().Be(
                $"One or more consumers are not connected:{Environment.NewLine}" +
                "- topic1 [00000000-0000-0000-0000-000000000000]");
        }
        public async Task StartAsync_ConnectAfterStartup_BrokerConnectedAfterLifetimeEvent()
        {
            var appStartedTokenSource = new CancellationTokenSource();
            var lifetimeEvents        = Substitute.For <IHostApplicationLifetime>();

            lifetimeEvents.ApplicationStarted.Returns(appStartedTokenSource.Token);

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddTransient(_ => lifetimeEvents)
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .WithConnectionOptions(
                        new BrokerConnectionOptions
            {
                Mode = BrokerConnectionMode.AfterStartup
            })));

            var service = serviceProvider.GetServices <IHostedService>().OfType <BrokerConnectorService>().Single();
            await service.StartAsync(CancellationToken.None);

            var testBroker = serviceProvider.GetRequiredService <TestBroker>();

            testBroker.IsConnected.Should().BeFalse();

            appStartedTokenSource.Cancel();

            testBroker.IsConnected.Should().BeTrue();
        }
        public async Task CheckHealthAsync_ConsumerReady_HealthyReturned()
        {
            var statusInfo = Substitute.For <IConsumerStatusInfo>();

            statusInfo.Status.Returns(ConsumerStatus.Ready);
            var consumer = Substitute.For <IConsumer>();

            consumer.StatusInfo.Returns(statusInfo);
            var broker = Substitute.For <IBroker>();

            broker.ProducerEndpointType.Returns(typeof(TestProducerEndpoint));
            broker.ConsumerEndpointType.Returns(typeof(TestConsumerEndpoint));
            broker.Consumers.Returns(new[] { consumer });

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddSilverback()
                .Services
                .AddSingleton <IBrokerCollection>(new BrokerCollection(new[] { broker }))
                .AddHealthChecks()
                .AddConsumersCheck());

            var(healthCheck, context) = GetHealthCheck(serviceProvider);

            var result = await healthCheck.CheckHealthAsync(context);

            result.Status.Should().Be(HealthStatus.Healthy);
        }
        public async Task CheckHealthAsync_WithCustomGracePeriod_CorrectStatusReturned()
        {
            var statusInfo = Substitute.For <IConsumerStatusInfo>();

            statusInfo.Status.Returns(ConsumerStatus.Connected);
            var consumer = Substitute.For <IConsumer>();

            consumer.StatusInfo.Returns(statusInfo);
            consumer.StatusInfo.History.Returns(
                new List <IConsumerStatusChange>
            {
                new ConsumerStatusChange(ConsumerStatus.Connected, DateTime.UtcNow.AddSeconds(-300)),
                new ConsumerStatusChange(ConsumerStatus.Ready, DateTime.UtcNow.AddSeconds(-120)),
                new ConsumerStatusChange(ConsumerStatus.Connected, DateTime.UtcNow.AddSeconds(-25))
            });
            var broker = Substitute.For <IBroker>();

            broker.ProducerEndpointType.Returns(typeof(TestProducerEndpoint));
            broker.ConsumerEndpointType.Returns(typeof(TestConsumerEndpoint));
            broker.Consumers.Returns(new[] { consumer });

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddSilverback()
                .Services
                .AddSingleton <IBrokerCollection>(new BrokerCollection(new[] { broker }))
                .AddHealthChecks()
                .AddConsumersCheck(gracePeriod: TimeSpan.FromSeconds(5)));

            var(healthCheck, context) = GetHealthCheck(serviceProvider);

            var result = await healthCheck.CheckHealthAsync(context);

            result.Status.Should().Be(HealthStatus.Unhealthy);
        }
        public async Task Publish_WithSortedBehaviors_BehaviorsExecutedInExpectedOrder()
        {
            var callsSequence   = new List <string>();
            var behavior1       = new TestSortedBehavior(100, callsSequence);
            var behavior2       = new TestSortedBehavior(50, callsSequence);
            var behavior3       = new TestSortedBehavior(-50, callsSequence);
            var behavior4       = new TestSortedBehavior(-100, callsSequence);
            var behavior5       = new TestBehavior(callsSequence);
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AddSingletonBehavior(behavior1)
                .AddScopedBehavior(_ => behavior2)
                .AddTransientBehavior(_ => behavior3)
                .AddSingletonBehavior(behavior4)
                .AddSingletonBehavior(behavior5));
            var publisher = serviceProvider.GetRequiredService <IPublisher>();

            publisher.Publish(new TestCommandOne());
            await publisher.PublishAsync(new TestCommandOne());

            callsSequence.Should().BeEquivalentTo(
                new[]
            {
                "-100", "-50", "unsorted", "50", "100",
                "-100", "-50", "unsorted", "50", "100"
            },
                options => options.WithStrictOrdering());
        }
Ejemplo n.º 12
0
        public async Task Publish_EnvelopesWithFilter_FilteredEnvelopesAndMessagesReceived()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AddScopedSubscriber <TestFilteredSubscriber>());
            var publisher          = serviceProvider.GetRequiredService <IPublisher>();
            var filteredSubscriber = serviceProvider.GetRequiredService <TestFilteredSubscriber>();

            publisher.Publish(new TestEnvelope(new TestEventOne {
                Message = "yes"
            }));
            publisher.Publish(new TestEnvelope(new TestEventOne {
                Message = "no"
            }));
            await publisher.PublishAsync(new TestEnvelope(new TestEventOne {
                Message = "yes"
            }));

            await publisher.PublishAsync(new TestEnvelope(new TestEventOne {
                Message = "no"
            }));

            filteredSubscriber.ReceivedEnvelopesCount.Should().Be(2);
            filteredSubscriber.ReceivedMessagesCount.Should().Be(2);
        }
Ejemplo n.º 13
0
        public async Task AddOutbound_WithIdempotentRegistration_LogCriticalWhenConfigurationDiffers()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddLoggerSubstitute()
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>())
                .AddEndpoints(
                    endpoints =>
                    endpoints
                    .AddOutbound <TestEventOne>(new TestProducerEndpoint("test1"))
                    .AddOutbound <TestEventOne>(
                        new TestProducerEndpoint("test1")
            {
                Chunk = new ChunkSettings {
                    AlwaysAddHeaders = true, Size = 200
                }
            })));

            var broker           = serviceProvider.GetRequiredService <TestBroker>();
            var loggerSubstitute =
                (LoggerSubstitute <EndpointsConfigurationBuilder>)serviceProvider
                .GetRequiredService <ILogger <EndpointsConfigurationBuilder> >();

            await broker.ConnectAsync();

            loggerSubstitute.Received(
                LogLevel.Critical,
                typeof(EndpointConfigurationException),
                null,
                1102,
                "An endpoint 'test1' for message type 'Silverback.Tests.Types.Domain.TestEventOne' but with a different configuration is already registered.");
        }
Ejemplo n.º 14
0
        public async Task AddOutbound_WithIdempotentRegistration_RegisterMultipleTimesWhenAllowed()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .AllowDuplicateEndpointRegistrations())
                .AddEndpoints(
                    endpoints =>
                    endpoints
                    .AddOutbound <TestEventOne>(new TestProducerEndpoint("test1"))
                    .AddOutbound <TestEventOne>(new TestProducerEndpoint("test1"))));

            var broker = serviceProvider.GetRequiredService <TestBroker>();
            await broker.ConnectAsync();

            var publisher = serviceProvider.GetRequiredService <IPublisher>();

            await publisher.PublishAsync(new TestEventOne());

            broker.ProducedMessages.Should().HaveCount(2);
        }
Ejemplo n.º 15
0
        ConnectAsyncAndDisconnectAsync_WithMultipleBrokers_AllBrokersConnectedAndDisconnected()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .AddBroker <TestOtherBroker>()));

            var brokerCollection = serviceProvider.GetRequiredService <IBrokerCollection>();

            brokerCollection[0].IsConnected.Should().BeFalse();
            brokerCollection[1].IsConnected.Should().BeFalse();

            await brokerCollection.ConnectAsync();

            brokerCollection[0].IsConnected.Should().BeTrue();
            brokerCollection[1].IsConnected.Should().BeTrue();

            await brokerCollection.DisconnectAsync();

            brokerCollection[0].IsConnected.Should().BeFalse();
            brokerCollection[1].IsConnected.Should().BeFalse();
        }
Ejemplo n.º 16
0
        public async Task Publish_MultipleDelegateSubscribersReturnMessagesAsyncEnumerable_MessagesRepublished()
        {
            var republishedMessages = new List <object>();
            var serviceProvider     = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AddDelegateSubscriber(
                    (TestEventTwo _) => new ICommand[]
            {
                new TestCommandOne(),
                new TestCommandTwo(),
                new TestCommandOne()
            }.ToAsyncEnumerable())
                .AddDelegateSubscriber(
                    (TestEventTwo _) => new List <ICommand>
            {
                new TestCommandOne(),
                new TestCommandTwo(),
                new TestCommandOne()
            }.ToAsyncEnumerable())
                .AddDelegateSubscriber((ICommand message) => republishedMessages.Add(message)));
            var publisher = serviceProvider.GetRequiredService <IPublisher>();

            publisher.Publish(new TestEventTwo());
            await publisher.PublishAsync(new TestEventTwo());

            republishedMessages.Should().HaveCount(12);
        }
        public async Task Publish_ToDelegateSubscriberWithAdditionalParameters_MessagesReceived()
        {
            int count           = 0;
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AddDelegateSubscriber <object>(
                    (_, forwardedServiceProvider) =>
            {
                if (forwardedServiceProvider != null)
                {
                    count++;
                }
            }));
            var publisher = serviceProvider.GetRequiredService <IPublisher>();

            publisher.Publish(new TestCommandOne());
            await publisher.PublishAsync(new TestCommandOne());

            publisher.Publish(new TestCommandTwo());
            await publisher.PublishAsync(new TestCommandTwo());

            count.Should().Be(4);
        }
Ejemplo n.º 18
0
        public async Task StartAsync_ApplicationStopping_BrokerGracefullyDisconnectedRegardlessOfMode(
            BrokerConnectionMode mode)
        {
            var appStoppingTokenSource = new CancellationTokenSource();
            var lifetimeEvents         = Substitute.For <IApplicationLifetime>();

            lifetimeEvents.ApplicationStopping.Returns(appStoppingTokenSource.Token);

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddTransient(_ => lifetimeEvents)
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .WithConnectionOptions(
                        new BrokerConnectionOptions
            {
                Mode = mode
            })));

            var service = serviceProvider.GetServices <IHostedService>().OfType <BrokerConnectorService>().Single();
            await service.StartAsync(CancellationToken.None);

            var testBroker = serviceProvider.GetRequiredService <TestBroker>();
            await testBroker.ConnectAsync();

            testBroker.IsConnected.Should().BeTrue();

            appStoppingTokenSource.Cancel();

            testBroker.IsConnected.Should().BeFalse();
        }
        public async Task Publish_ToMultipleSubscribers_MessagesReceived()
        {
            int delegateCount   = 0;
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AddSingletonSubscriber <TestSubscriber>()
                .AddDelegateSubscriber(
                    (object _) =>
            {
                delegateCount++;
                return(Task.CompletedTask);
            }));
            var publisher  = serviceProvider.GetRequiredService <IPublisher>();
            var subscriber = serviceProvider.GetRequiredService <TestSubscriber>();

            publisher.Publish(new TestCommandOne());
            await publisher.PublishAsync(new TestCommandOne());

            publisher.Publish(new TestCommandTwo());
            await publisher.PublishAsync(new TestCommandTwo());

            subscriber.ReceivedMessagesCount.Should().Be(4);
            subscriber.ReceivedCallsCount.Should().Be(12);
            delegateCount.Should().Be(4);
        }
Ejemplo n.º 20
0
        public async Task StartAsync_ExceptionWithRetryDisabled_ConnectNotRetried()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddTransient(_ => Substitute.For <IApplicationLifetime>())
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .WithConnectionOptions(
                        new BrokerConnectionOptions
            {
                Mode           = BrokerConnectionMode.Startup,
                RetryOnFailure = false
            })));

            var testBroker = serviceProvider.GetRequiredService <TestBroker>();

            testBroker.SimulateConnectIssues = true;

            var service = serviceProvider.GetServices <IHostedService>().OfType <BrokerConnectorService>().Single();
            await service.StartAsync(CancellationToken.None);

            testBroker.IsConnected.Should().BeFalse();
        }
        public async Task Publish_StreamProviderOfEnvelopes_OnlyMatchingUnwrappedMessagesReceived()
        {
            var receivedStreamsOfOnes = 0;
            var receivedTestEventOnes = 0;
            var receivedStreamsOfTwos = 0;
            var receivedTestEventTwos = 0;

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AddDelegateSubscriber(
                    (IMessageStreamEnumerable <TestEventOne> enumerable) =>
            {
                Interlocked.Increment(ref receivedStreamsOfOnes);
                foreach (var dummy in enumerable)
                {
                    Interlocked.Increment(ref receivedTestEventOnes);
                }
            })
                .AddDelegateSubscriber(
                    (IMessageStreamEnumerable <TestEventTwo> enumerable) =>
            {
                Interlocked.Increment(ref receivedStreamsOfTwos);
                foreach (var dummy in enumerable)
                {
                    Interlocked.Increment(ref receivedTestEventTwos);
                }
            }));
            var streamPublisher = serviceProvider.GetRequiredService <IStreamPublisher>();

            var stream = new MessageStreamProvider <IEnvelope>();
            await streamPublisher.PublishAsync(stream);

            await stream.PushAsync(new TestEnvelope(new TestEventTwo()));

            await stream.PushAsync(new TestEnvelope(new TestEventTwo()));

            await AsyncTestingUtil.WaitAsync(() => receivedTestEventTwos >= 2);

            receivedStreamsOfOnes.Should().Be(0);
            receivedTestEventOnes.Should().Be(0);
            receivedStreamsOfTwos.Should().Be(1);
            receivedTestEventTwos.Should().Be(2);

            await stream.PushAsync(new TestEnvelope(new TestEventOne()));

            await stream.PushAsync(new TestEnvelope(new TestEventTwo()));

            await stream.PushAsync(new TestEnvelope(new TestEventOne()));

            await stream.PushAsync(new TestEnvelope(new TestEventTwo()));

            await AsyncTestingUtil.WaitAsync(() => receivedTestEventTwos >= 4);

            receivedStreamsOfOnes.Should().Be(1);
            receivedTestEventOnes.Should().Be(2);
            receivedStreamsOfTwos.Should().Be(1);
            receivedTestEventTwos.Should().Be(4);
        }
Ejemplo n.º 22
0
        public async Task Publish_MessageStreamProvider_MessagesNotAutomaticallyEnumerated()
        {
            var receivedEnumeratedStreams = 0;

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AsObservable()
                .AddDelegateSubscriber(
                    (IReadOnlyCollection <IEvent> _) =>
            {
                Interlocked.Increment(ref receivedEnumeratedStreams);
            })
                .AddDelegateSubscriber(
                    (List <TestEventOne> _) => { Interlocked.Increment(ref receivedEnumeratedStreams); }));
            var streamPublisher = serviceProvider.GetRequiredService <IStreamPublisher>();

            var streamProvider = new MessageStreamProvider <IEvent>();

            await streamPublisher.PublishAsync(streamProvider);

            await streamProvider.PushAsync(new TestEventOne(), false);

            await streamProvider.PushAsync(new TestEventTwo(), false);

            await streamProvider.CompleteAsync();

            await AsyncTestingUtil.WaitAsync(
                () => receivedEnumeratedStreams >= 1,
                TimeSpan.FromMilliseconds(500));

            receivedEnumeratedStreams.Should().Be(0);
        }
Ejemplo n.º 23
0
        public async Task Publish_MessageStreamProviderOfEnvelopes_OnlyAutoUnwrapMessagesReceived()
        {
            var receivedEvents = new List <IEvent>();

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AsObservable()
                .AddDelegateSubscriber(
                    (IMessageStreamObservable <IEvent> observable) =>
            {
                observable.Subscribe(message => receivedEvents.Add(message));
            }));
            var streamPublisher = serviceProvider.GetRequiredService <IStreamPublisher>();

            var streamProvider = new MessageStreamProvider <IEnvelope>();
            await streamPublisher.PublishAsync(streamProvider);

            await streamProvider.PushAsync(new TestEnvelope(new TestEventOne(), false), false);

            await streamProvider.PushAsync(new TestEnvelope(new TestEventTwo()));

            await AsyncTestingUtil.WaitAsync(() => receivedEvents.Count >= 1);

            receivedEvents.Should().HaveCount(1);
            receivedEvents[0].Should().BeOfType <TestEventTwo>();
        }
Ejemplo n.º 24
0
        public async Task AddInbound_WithMultipleBrokers_ConsumersCorrectlyConnected()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(
                    options => options
                    .AddBroker <TestBroker>()
                    .AddBroker <TestOtherBroker>())
                .AddEndpoints(
                    endpoints =>
                    endpoints
                    .AddInbound(new TestConsumerEndpoint("test1"))
                    .AddInbound(new TestOtherConsumerEndpoint("test2"))));

            var broker = serviceProvider.GetRequiredService <TestBroker>();
            await broker.ConnectAsync();

            var otherBroker = serviceProvider.GetRequiredService <TestOtherBroker>();
            await otherBroker.ConnectAsync();

            broker.Consumers.Should().HaveCount(1);
            otherBroker.Consumers.Should().HaveCount(1);
        }
Ejemplo n.º 25
0
        public async Task Publish_MessageStreamProvider_OnlyRequiredStreamsPublished()
        {
            var receivedStreams = 0;

            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .AsObservable()
                .AddDelegateSubscriber(
                    (IMessageStreamObservable <IEvent> observable) =>
            {
                Interlocked.Increment(ref receivedStreams);
                observable.Subscribe(_ => { });
            })
                .AddDelegateSubscriber(
                    (IMessageStreamObservable <TestEventOne> observable) =>
            {
                Interlocked.Increment(ref receivedStreams);
                observable.Subscribe(_ => { });
            })
                .AddDelegateSubscriber(
                    (IMessageStreamObservable <TestCommandOne> observable) =>
            {
                Interlocked.Increment(ref receivedStreams);
                observable.Subscribe(_ => { });
            }));
            var streamPublisher = serviceProvider.GetRequiredService <IStreamPublisher>();

            var streamProvider1 = new MessageStreamProvider <IEvent>();
            var streamProvider2 = new MessageStreamProvider <IEvent>();

            await Task.Delay(100);

            receivedStreams.Should().Be(0);

            streamPublisher.Publish(streamProvider1);
            await streamPublisher.PublishAsync(streamProvider2);

            await streamProvider1.PushAsync(new TestEventTwo());

            await Task.Delay(100);

            receivedStreams.Should().Be(1);

            await streamProvider1.PushAsync(new TestEventOne());

            await AsyncTestingUtil.WaitAsync(() => receivedStreams >= 2);

            receivedStreams.Should().Be(2);

            await streamProvider2.PushAsync(new TestEventOne());

            await AsyncTestingUtil.WaitAsync(() => receivedStreams >= 4);

            receivedStreams.Should().Be(4);
        }
Ejemplo n.º 26
0
 public static IPublisher GetPublisher(Action <ISilverbackBuilder> buildAction)
 {
     return(ServiceProviderHelper.GetServiceProvider(
                services =>
     {
         var builder = services.AddSilverback().AsObservable();
         buildAction(builder);
     }).GetRequiredService <IPublisher>());
 }
Ejemplo n.º 27
0
        public KafkaBrokerTests()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddSilverback()
                .WithConnectionToMessageBroker(options => options.AddKafka()));

            _broker = serviceProvider.GetRequiredService <KafkaBroker>();
        }
Ejemplo n.º 28
0
        public RabbitBrokerTests()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(options => options.AddRabbit()));

            _broker = serviceProvider.GetRequiredService <RabbitBroker>();
        }
Ejemplo n.º 29
0
        public QueryPublisherTests()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .UseModel()
                .AddDelegateSubscriber((TestQuery _) => new[] { 1, 2, 3 }));

            _publisher = serviceProvider.CreateScope().ServiceProvider.GetRequiredService <IQueryPublisher>();
        }
Ejemplo n.º 30
0
        public EventPublisherTests()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .UseModel()
                .AddDelegateSubscriber((TestEvent _) => _receivedMessages++));

            _publisher = serviceProvider.CreateScope().ServiceProvider.GetRequiredService <IEventPublisher>();
        }