Example #1
0
    public async Task CanDoIt()
    {
        using var gotTheEvent = new ManualResetEvent(initialState: false);
        using var activator   = new BuiltinHandlerActivator();

        var subscriberStore = new InMemorySubscriberStore();
        var network         = new InMemNetwork();

        var starter = Configure.With(activator)
                      .Transport(t => t.UseInMemoryTransport(network, "buggerino"))
                      .Subscriptions(s => s.StoreInMemory(subscriberStore))
                      .Create();

        var publisher = Configure.With(Using(new BuiltinHandlerActivator()))
                        .Transport(t => t.UseInMemoryTransportAsOneWayClient(network))
                        .Subscriptions(s => s.StoreInMemory(subscriberStore))
                        .Start();

        Task Handle(ThisIsTheEventWeAreTalkingAbout configurationUpdatedEvent)
        {
            Console.WriteLine($"Got event: {configurationUpdatedEvent}");
            gotTheEvent.Set();
            return(Task.CompletedTask);
        }

        activator.Handle <ThisIsTheEventWeAreTalkingAbout>((ThisIsTheEventWeAreTalkingAbout e) => Handle(e));

        await starter.Bus.Subscribe(typeof(ThisIsTheEventWeAreTalkingAbout));

        starter.Start();

        await publisher.Publish(new ThisIsTheEventWeAreTalkingAbout());

        gotTheEvent.WaitOrDie(timeout: TimeSpan.FromSeconds(2));
    }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Register handlers
            // services.AutoRegisterHandlersFromAssemblyOf<Handler1>();


            // Configure and register Rebus

            var subscriberStore = new InMemorySubscriberStore();

            var accessKeyId     = Configuration.GetValue <string>("AWS:AccessKeyId");
            var secretAccessKey = Configuration.GetValue <string>("AWS:SecretAccessKey");

            services.AddRebus(configure => configure
                              .Logging(l => l.Serilog())
                              .Transport(t => t.UseAmazonSQS(accessKeyId, secretAccessKey, RegionEndpoint.EUWest2, "publisher"))
                              .Subscriptions(s => s.StoreInMemory(subscriberStore))
                              .Routing(r => r.TypeBased().Map <BusMessage>("rebusQueue"))

                              );
        }
Example #3
0
    protected override void SetUp()
    {
        // installs a transport decorator that throws an exception, if the sent message size exceeds the given threshold
        void FailIfMessageSizeExceeds(OptionsConfigurer optionsConfigurer, int messageSizeLimitBytes) =>
        optionsConfigurer.Decorate <ITransport>(c => new ThrowExceptionsOnBigMessagesTransportDecorator(c.Get <ITransport>(), messageSizeLimitBytes));

        _activator = new BuiltinHandlerActivator();

        Using(_activator);

        _subscriberStore = new InMemorySubscriberStore();
        _network         = new InMemNetwork();
        _dataStore       = new InMemDataStore();

        _starter = Configure.With(_activator)
                   .Transport(t => t.UseInMemoryTransport(_network, "automatic-claim-check"))
                   .Options(o => o.LogPipeline(verbose: true))
                   .Subscriptions(s => s.StoreInMemory(_subscriberStore))
                   .DataBus(d =>
        {
            d.SendBigMessagesAsAttachments(bodySizeThresholdBytes: limit / 2);

            d.StoreInMemory(_dataStore);
        })
                   .Options(o => FailIfMessageSizeExceeds(o, limit))
                   .Create();
    }
Example #4
0
        public CreateAccountMessageHandlerTests()
        {
            var subscriberStore = new InMemorySubscriberStore();
            var network         = new InMemNetwork();

            hostBuilder.ConfigureContainer <ContainerBuilder>(builder =>
            {
                builder.RegisterRebus((configurer, _) =>
                {
                    return(configurer
                           .Transport(t => t.UseInMemoryTransport(network, _queueName))
                           .Subscriptions(s => s.StoreInMemory(subscriberStore))
                           .Options(b => b.SimpleRetryStrategy(maxDeliveryAttempts: 1))
                           .Events(e =>
                    {
                        e.AfterMessageHandled += (bus, hdrs, msg, ctx, args) => _messageProccessedEvent.Set();
                    }));
                });

                builder.RegisterHandler <CreateAccountMessageHandler>();
            });

            var publisherActivator = new BuiltinHandlerActivator();

            _publisher = Configure.With(publisherActivator)
                         .Transport(t => t.UseInMemoryTransportAsOneWayClient(network))
                         .Subscriptions(s => s.StoreInMemory(subscriberStore))
                         .Start();

            _host = hostBuilder.Start();
        }
    protected override void SetUp()
    {
        base.SetUp();

        SqlTestHelper.DropTable("RebusOutbox");

        _network         = new InMemNetwork();
        _subscriberStore = new InMemorySubscriberStore();
    }
Example #6
0
        public static IServiceCollection AddRebus(this IServiceCollection services)
        {
            var subscriberStore = new InMemorySubscriberStore();

            services.AddRebus(configure => configure
                              .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "Messages"))
                              .Subscriptions(s => s.StoreInMemory(subscriberStore))
                              .Routing(r => r.TypeBased().MapAssemblyOf <SimulacaoCommandHandler>("Messages")));
            return(services);
        }
        public async Task ItWillWorkWihoutNativeSubscriptionStorage()
        {
            var store = new InMemorySubscriberStore();

            var gotExpectedMessages = Using(new ManualResetEvent(initialState: false));
            var receiver            = Using(new BuiltinHandlerActivator());

            receiver.Register(() => new SomeSimpleHandler(gotExpectedMessages));


            var receiverBus = Configure.With(receiver)
                              .Transport(t => t.UsePubSubAndPurgeQueueAtStartup(Constants.Receiver))
                              .Subscriptions(s => s.StoreInMemory(store))
                              .Start();


            await receiverBus.Subscribe <MessageToSubscribeA>();

            await receiverBus.Subscribe <MessageToSubscribeB>();

            var sender = Configure.With(Using(new BuiltinHandlerActivator()))
                         .Transport(t => t.UsePubSubAndPurgeQueueAtStartup(Constants.Sender))
                         .Subscriptions(s => s.StoreInMemory(store))
                         .Routing(t => t.TypeBased().Map <string>(Constants.Receiver))
                         .Start();

            await sender.Send("Some fancy message");

            await sender.Publish(new MessageToSubscribeA()
            {
                Data = "MessageToSubscribeA"
            });

            await sender.Publish(new MessageToSubscribeB()
            {
                Data = "MessageToSubscribeB"
            });

            await sender.Publish(new MessageToSubscribeC()
            {
                Data = "MessageToSubscribeC"
            });



            var wait = TimeSpan.FromSeconds(20);

            gotExpectedMessages.WaitOrDie(
                timeout: wait,
                errorMessage: $"Did not receive expected messages"
                );
        }
        protected override void SetUp()
        {
            _network         = new InMemNetwork();
            _subscriberStore = new InMemorySubscriberStore();

            _activator = new BuiltinHandlerActivator();

            Using(_activator);

            _starter = Configure.With(_activator)
                       .Transport(t => t.UseInMemoryTransport(_network, "endpoint1"))
                       .Subscriptions(s => s.StoreInMemory(_subscriberStore))
                       .Create();
        }
Example #9
0
        public async Task ActuallyPassesActivityToHandlerOnOtherSide()
        {
            var network         = new InMemNetwork();
            var subscriberStore = new InMemorySubscriberStore();

            using var publisherActivator  = new BuiltinHandlerActivator();
            using var subscriberActivator = new BuiltinHandlerActivator();
            using var eventWasReceived    = new ManualResetEvent(initialState: false);

            var publisher = Configure.With(publisherActivator)
                            .Transport(t => t.UseInMemoryTransport(network, "publisher"))
                            .Subscriptions(s => s.StoreInMemory(subscriberStore))
                            .Options(o => o.EnableDiagnosticSources())
                            .Start();

            var rootActivity = new Activity("root");

            rootActivity.SetIdFormat(ActivityIdFormat.W3C);

            subscriberActivator.Handle <string>(_ =>
            {
                var act = Activity.Current !;
                Assert.That(act, Is.Not.Null);
                Assert.That(act.RootId, Is.EqualTo(rootActivity.RootId));
                Assert.That(act.Id, Is.Not.EqualTo(rootActivity.RootId));

                // ReSharper disable once AccessToDisposedClosure
                eventWasReceived.Set();

                Assert.That(act.GetBaggageItem("MyBaggage"), Is.EqualTo("Hej Verden!"));

                return(Task.CompletedTask);
            });

            var subscriber = Configure.With(subscriberActivator)
                             .Transport(t => t.UseInMemoryTransport(network, "subscriber"))
                             .Subscriptions(s => s.StoreInMemory(subscriberStore))
                             .Options(o => o.EnableDiagnosticSources())
                             .Start();

            await subscriber.Subscribe <string>();

            rootActivity.AddBaggage("MyBaggage", "Hej Verden!");
            rootActivity.Start();
            await publisher.Publish("Super Duper fed besked");

            Assert.That(eventWasReceived.WaitOne(TimeSpan.FromSeconds(5)), Is.True, "Did not receive the published event within 5 seconds");
        }
Example #10
0
        protected override void SetUp()
        {
            var network         = new InMemNetwork();
            var subscriberStore = new InMemorySubscriberStore();

            _publisher = GetEndpoint(network, "publisher", c =>
            {
                c.Subscriptions(s => s.StoreInMemory(subscriberStore));
                c.Routing(r => r.TypeBased());
            });

            _client1GotTheEvent = new ManualResetEvent(false);
            _client1            = GetEndpoint(network, "client1", c =>
            {
                c.Routing(r => r.TypeBased().Map <SomeKindOfEvent>("publisher"));
            });
            _client1.AddHandlerWithBusTemporarilyStopped <SomeKindOfEvent>(async e => _client1GotTheEvent.Set());
        }
        public void OnlyReceivesPublishedEventWhenRebusTransactionScopeIsCompleted()
        {
            var network         = new InMemNetwork();
            var subscriberStore = new InMemorySubscriberStore();

            network.CreateQueue("subscriber");
            subscriberStore.AddSubscriber(typeof(TestEvent).GetSimpleAssemblyQualifiedName(), "subscriber");

            var bus = Configure.With(new BuiltinHandlerActivator())
                      .Subscriptions(config => config.StoreInMemory(subscriberStore))
                      .Transport(configurer => configurer.UseInMemoryTransport(network, "Test"))
                      .Start();

            using (var scope = new RebusTransactionScope())
            {
                bus.Advanced.SyncBus.Publish(new TestEvent("completed"));
                scope.Complete();
            }

            using (new RebusTransactionScope())
            {
                bus.Advanced.SyncBus.Publish(new TestEvent("not completed"));
                // this scope is intentionally not completed!
            }

            var messages = network.GetMessages("subscriber").ToList();

            Assert.That(messages.Count, Is.EqualTo(1));

            var transportMessage = messages.First();

            Assert.That(transportMessage.Headers.GetValue(Headers.Type), Is.EqualTo(typeof(TestEvent).GetSimpleAssemblyQualifiedName()));

            var json      = Encoding.UTF8.GetString(transportMessage.Body);
            var testEvent = JsonConvert.DeserializeObject <TestEvent>(json);

            Assert.That(testEvent.Label, Is.EqualTo("completed"));
        }
Example #12
0
    public async Task ActivatorNotNecessary()
    {
        // Arrange
        var message    = new Message(Guid.NewGuid());
        var hypothesis = Hypothesis.For <Message>()
                         .Any(m => m == message);

        using var activator = new BuiltinHandlerActivator()
                              .Register(hypothesis.AsHandler);

        var network         = new InMemNetwork();
        var subscriberStore = new InMemorySubscriberStore();

        using var subscriber = await Subscriber(activator, network, subscriberStore);

        using var publisher = Publisher(network, subscriberStore);

        // Act
        await publisher.Publish(message);

        // Assert
        await hypothesis.Validate(TimeSpan.FromSeconds(5));
    }
Example #13
0
 public void SetUp()
 {
     _inMemorySubscriberStore = new InMemorySubscriberStore();
 }
Example #14
0
 private static IBus Publisher(InMemNetwork network, InMemorySubscriberStore subscriberStore) =>
 Configure.OneWayClient()
 .Transport(t => t.UseInMemoryTransportAsOneWayClient(network))
 .Subscriptions(s => s.StoreInMemory(subscriberStore))         // req'd also for one way client transports
 .Start();
Example #15
0
    private static async Task <IBus> Subscriber(IHandlerActivator activator, InMemNetwork network, InMemorySubscriberStore subscriberStore)
    {
        var subscriber = Configure.With(activator)
                         .Transport(t => t.UseInMemoryTransport(network, "subscriber"))
                         .Subscriptions(s => s.StoreInMemory(subscriberStore))
                         .Start();

        await subscriber.Subscribe <Message>();

        return(subscriber);
    }
 /// <summary>
 /// Configures Rebus to store subscriptions in memory. The subscription storage is assumed to be CENTRALIZED
 /// with this overload because a <see cref="InMemorySubscriberStore"/> is passed in.  PLEASE NOTE that this
 /// is probably not useful for any other scenario  than TESTING because usually you want subscriptions to be PERSISTENT.
 /// </summary>
 public static void StoreInMemory(this StandardConfigurer <ISubscriptionStorage> configurer, InMemorySubscriberStore subscriberStore)
 {
     if (configurer == null)
     {
         throw new ArgumentNullException(nameof(configurer));
     }
     if (subscriberStore == null)
     {
         throw new ArgumentNullException(nameof(subscriberStore));
     }
     configurer.Register(c => new InMemorySubscriptionStorage(subscriberStore));
 }
 protected override void SetUp()
 {
     _subscriberStore = new InMemorySubscriberStore();
     _network         = new InMemNetwork();
     _dataStore       = new InMemDataStore();
 }
 public InMemorySubscriptionConfigurer(InMemorySubscriberStore store)
 {
     _store = store;
 }
 InMemorySubscriptionStorage(InMemorySubscriberStore subscriberStore, bool isCentralized)
 {
     _subscriberStore = subscriberStore ?? throw new ArgumentNullException(nameof(subscriberStore));
     IsCentralized    = isCentralized;
 }
 /// <summary>
 /// Creates the in-mem subscription storage as a centralized subscription storage, using the given
 /// <see cref="InMemorySubscriberStore"/> to share subscriptions
 /// </summary>
 public InMemorySubscriptionStorage(InMemorySubscriberStore subscriberStore) : this(subscriberStore, true)
 {
 }