Exemplo n.º 1
0
        protected SagaTestHarness()
        {
            _host = JasperHost.For(_ =>
            {
                _.Handlers.DisableConventionalDiscovery().IncludeType <TSagaHandler>();
                _.MartenConnectionStringIs(Servers.PostgresConnectionString);
                _.Include <MartenBackedPersistence>();

                _.Include <MessageTrackingExtension>();

                _.Settings.ConfigureMarten(x =>
                {
                    x.DatabaseSchemaName      = "sagas";
                    x.AutoCreateSchemaObjects = AutoCreate.All;
                }
                                           );

                _.Publish.AllMessagesTo(TransportConstants.LoopbackUri);

                configure(_);
            });

            _history = _host.Get <MessageHistory>();

            var store = _host.Get <IDocumentStore>();

            store.Advanced.Clean.CompletelyRemoveAll();
        }
Exemplo n.º 2
0
        public override void SetUp()
        {
            _envelopes.Clear();
            _nodeLockers.Clear();

            _workers        = new RecordingWorkerQueue();
            _schedulerAgent = new RecordingSchedulingAgent();

            _host = JasperHost.For(_ =>
            {
                _.Settings.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString);

                _.Services.AddSingleton <IWorkerQueue>(_workers);
                _.Services.AddSingleton <IDurabilityAgent>(_schedulerAgent);


                _.Settings.Alter <JasperOptions>(x =>
                {
                    x.Retries.FirstNodeReassignmentExecution = 30.Minutes();
                    x.ScheduledJobs.FirstExecution           = 30.Minutes();
                    x.Retries.FirstNodeReassignmentExecution = 30.Minutes();
                    x.Retries.NodeReassignmentPollingTime    = 30.Minutes();
                });
            });

            _host.Get <IEnvelopePersistence>().Admin.ClearAllPersistedEnvelopes();

            _serializers = _host.Get <MessagingSerializationGraph>();

            _host.RebuildMessageStorage();

            _currentNodeId = _host.Get <JasperOptions>().UniqueNodeId;

            _owners["This Node"] = _currentNodeId;
        }
Exemplo n.º 3
0
        public void ChannelIsLatched(Uri channel)
        {
            getStubTransport().Channels[channel].Latched = true;

            // Gotta do this so that the query on latched channels works correctly
            _host.Get <ISubscriberGraph>().GetOrBuild(channel);
        }
Exemplo n.º 4
0
        public void can_get_storage_sql()
        {
            var sql = theSender.Get <IEnvelopePersistence>().Admin.CreateSql();

            sql.ShouldNotBeNull();

            _output.WriteLine(sql);
        }
Exemplo n.º 5
0
        public void codegen_document_session_creation()
        {
            var handlerGraph   = runtime.Get <HandlerGraph>();
            var messageHandler = handlerGraph.HandlerFor <CreateFakeDoc>();

            messageHandler
            .Chain.SourceCode.ShouldContain("var documentSession = _documentStore.LightweightSession()");
        }
Exemplo n.º 6
0
        public MessageHandler HandlerFor <TMessage>()
        {
            if (_host == null)
            {
                _host = JasperHost.For(theRegistry);
            }


            return(_host.Get <HandlerGraph>().HandlerFor(typeof(TMessage)));
        }
Exemplo n.º 7
0
        private async Task assertIncomingEnvelopesIsZero()
        {
            var receiverCounts = await theReceiver.Get <IEnvelopePersistence>().Admin.GetPersistedCounts();

            if (receiverCounts.Incoming > 0)
            {
                await Task.Delay(500.Milliseconds());

                receiverCounts = await theReceiver.Get <IEnvelopePersistence>().Admin.GetPersistedCounts();
            }

            StoryTellerAssert.Fail(receiverCounts.Incoming > 0, "There are still persisted, incoming messages");
        }
        /// <summary>
        ///     Executes an action and waits until the execution and all cascading messages
        ///     have completed
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static async Task ExecuteAndWait(this IJasperHost runtime, Func <IMessageContext, Task> action,
                                                bool assertNoExceptions = false)
        {
            runtime.validateMessageTrackerExists();

            var history = runtime.Get <MessageHistory>();
            var context = runtime.Get <IMessageContext>();
            await history.WatchAsync(() => action(context));

            if (assertNoExceptions)
            {
                history.AssertNoExceptions();
            }
        }
Exemplo n.º 9
0
 protected override ItemCreated loadItem(IJasperHost receiver, Guid id)
 {
     using (var session = receiver.Get <IDocumentStore>().QuerySession())
     {
         return(session.Load <ItemCreated>(id));
     }
 }
Exemplo n.º 10
0
        public override void SetUp()
        {
            _envelopes.Clear();
            _nodeLockers.Clear();

            _workers = new RecordingWorkerQueue();

            _host = JasperHost.CreateDefaultBuilder()
                    .UseJasper(_ =>
            {
                _.ServiceName = Guid.NewGuid().ToString();

                _.MartenConnectionStringIs(Servers.PostgresConnectionString);

                _.Services.AddSingleton <IWorkerQueue>(_workers);

                _.Include <MartenBackedPersistence>();

                _.Settings.Alter <JasperOptions>(x =>
                {
                    x.Retries.FirstNodeReassignmentExecution = 30.Minutes();
                    x.ScheduledJobs.FirstExecution           = 30.Minutes();
                    x.Retries.FirstNodeReassignmentExecution = 30.Minutes();
                    x.Retries.NodeReassignmentPollingTime    = 30.Minutes();
                });
            })
                    .StartJasper();


            _admin = _host.Get <IEnvelopePersistence>().Admin;
            _admin.RebuildSchemaObjects();

            _settings    = _host.Get <PostgresqlSettings>();
            _serializers = _host.Get <MessagingSerializationGraph>();

            theStore = _host.Get <IDocumentStore>();
            theStore.Advanced.Clean.DeleteAllDocuments();

            _currentNodeId = _host.Get <JasperOptions>().UniqueNodeId;

            _owners["This Node"] = _currentNodeId;
        }
Exemplo n.º 11
0
        public override void SetUp()
        {
            _tracker = new AttemptTracker();

            var registry = new JasperRegistry();

            registry.Transports.ListenForMessagesFrom("stub://1".ToUri());
            registry.Services.AddSingleton(_tracker);
            registry.Publish.Message <ErrorCausingMessage>()
            .To("stub://1".ToUri());

            _host = JasperHost.For(registry);

            _transport = _host.GetStubTransport();

            _graph = _host.Get <HandlerGraph>();
            _chain = _graph.ChainFor <ErrorCausingMessage>();


            _bus = _host.Get <IMessageContext>();
        }
Exemplo n.º 12
0
        public async Task tags_the_envelope_with_the_source()
        {
            getReady();

            var waiter = theTracker.WaitFor <Message2>();

            await theSender.Messaging.Send(theAddress, new Message2());

            var env = await waiter;

            env.Source.ShouldBe(theSender.Get <JasperOptions>().NodeId);
        }
Exemplo n.º 13
0
        public async Task enqueue_locally()
        {
            var item = new ItemCreated
            {
                Name = "Shoe",
                Id   = Guid.NewGuid()
            };

            var waiter = theTracker.WaitFor <ItemCreated>();

            await theReceiver.Messaging.Enqueue(item);

            waiter.Wait(5.Seconds());

            waiter.IsCompleted.ShouldBeTrue();

            var documentStore = theReceiver.Get <IDocumentStore>();

            using (var session = documentStore.QuerySession())
            {
                var item2 = session.Load <ItemCreated>(item.Id);
                if (item2 == null)
                {
                    Thread.Sleep(500);
                    item2 = session.Load <ItemCreated>(item.Id);
                }


                item2.Name.ShouldBe("Shoe");
            }

            var incoming = await theReceiver.Get <IEnvelopePersistence>().Admin.AllIncomingEnvelopes();

            incoming.Any().ShouldBeFalse();
        }
        /// <summary>
        ///     Invoke a message through IServiceBus.Invoke(msg) and wait until all processing
        ///     of the original message and cascading messages are complete
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static async Task ExecuteAndWait(this IJasperHost runtime, Func <Task> action,
                                                int timeoutInMilliseconds = 5000, bool assertNoExceptions = false)
        {
            runtime.validateMessageTrackerExists();

            var history = runtime.Get <MessageHistory>();
            await history.WatchAsync(action, timeoutInMilliseconds);

            if (assertNoExceptions)
            {
                history.AssertNoExceptions();
            }
        }
        /// <summary>
        ///     Executes an action and waits until the execution and all cascading messages
        ///     have completed
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static async Task ExecuteAndWait(this IJasperHost runtime, Action action,
                                                bool assertNoExceptions = false)
        {
            runtime.validateMessageTrackerExists();

            var history = runtime.Get <MessageHistory>();
            await history.Watch(action);

            if (assertNoExceptions)
            {
                history.AssertNoExceptions();
            }
        }
        /// <summary>
        ///     Send a message through the service bus and wait until that message
        ///     and all cascading messages have been successfully processed
        /// </summary>
        /// <param name="runtime"></param>
        /// <param name="message"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static async Task SendMessageAndWait <T>(this IJasperHost runtime, T message,
                                                        int timeoutInMilliseconds = 5000, bool assertNoExceptions = false)
        {
            runtime.validateMessageTrackerExists();

            var history = runtime.Get <MessageHistory>();
            await history.WatchAsync(() => runtime.Messaging.Send(message), timeoutInMilliseconds);

            if (assertNoExceptions)
            {
                history.AssertNoExceptions();
            }
        }
Exemplo n.º 17
0
        public void ForMessage([SelectionList("MessageTypes")] string MessageType)
        {
            var messageType = messageTypeFor(MessageType);

            if (_host == null)
            {
                _host = JasperHost.For(_registry);
            }

            var router = _host.Get <IMessageRouter>();

            _tracks = router.Route(messageType);
        }
Exemplo n.º 18
0
        protected override async Task withContext(IJasperHost sender, IMessageContext context,
                                                  Func <IMessageContext, Task> action)
        {
            var senderStore = sender.Get <IDocumentStore>();

            using (var session = senderStore.LightweightSession())
            {
                await context.EnlistInTransaction(session);

                await action(context);

                await session.SaveChangesAsync();
            }
        }
Exemplo n.º 19
0
        public void Describe(IJasperHost runtime, TextWriter writer)
        {
            var settings = runtime.Get <JasperOptions>();

            var transports = runtime.Get <ITransport[]>()
                             .Where(x => settings.StateFor(x.Protocol) == TransportState.Enabled);

            foreach (var transport in transports)
            {
                transport.Describe(writer);
            }

            writer.WriteLine();
            foreach (var channel in Subscribers.AllKnown())
            {
                writer.WriteLine($"Active sending agent to {channel.Uri}");
            }

            if (Graph.Chains.Any())
            {
                writer.WriteLine("Handles messages:");

                var longestMessageName = Graph.Chains.Select(x => x.MessageType.NameInCode().Length).Max() + 2;

                foreach (var chain in Graph.Chains)
                {
                    var messageName = chain.MessageType.NameInCode().PadLeft(longestMessageName);
                    var handlers    = chain.Handlers.Select(x => x.ToString()).Join(", ");


                    writer.WriteLine($"{messageName}: {handlers}");
                }
            }


            writer.WriteLine();
        }
        public async Task get_counts()
        {
            var thePersistor = theHost.Get <PostgresqlEnvelopePersistence>();

            var list = new List <Envelope>();

            // 10 incoming
            for (var i = 0; i < 10; i++)
            {
                var envelope = ObjectMother.Envelope();
                envelope.Status = TransportConstants.Incoming;

                list.Add(envelope);
            }

            await thePersistor.StoreIncoming(list.ToArray());


            // 7 scheduled
            list.Clear();
            for (var i = 0; i < 7; i++)
            {
                var envelope = ObjectMother.Envelope();
                envelope.Status = TransportConstants.Scheduled;

                list.Add(envelope);
            }

            await thePersistor.StoreIncoming(list.ToArray());


            // 3 outgoing
            list.Clear();
            for (var i = 0; i < 3; i++)
            {
                var envelope = ObjectMother.Envelope();
                envelope.Status = TransportConstants.Outgoing;

                list.Add(envelope);
            }

            await thePersistor.StoreOutgoing(list.ToArray(), 0);

            var counts = await thePersistor.Admin.GetPersistedCounts();

            counts.Incoming.ShouldBe(10);
            counts.Scheduled.ShouldBe(7);
            counts.Outgoing.ShouldBe(3);
        }
Exemplo n.º 21
0
        protected void withApplication()
        {
            _host = JasperHost.For(_ =>
            {
                _.Handlers.DisableConventionalDiscovery().IncludeType <TSagaHandler>();

                _.Include <MessageTrackingExtension>();

                _.Publish.AllMessagesTo(TransportConstants.LoopbackUri);

                configure(_);
            });

            _history = _host.Get <MessageHistory>();
        }
Exemplo n.º 22
0
 public IGrammar IfTheApplicationIs()
 {
     return(Embed <ServiceBusApplication>("If a service bus application is configured to")
            .After(c =>
     {
         _host = c.State.Retrieve <IJasperHost>();
         try
         {
             _host.Get <IEnvelopePersistence>().Admin.ClearAllPersistedEnvelopes();
         }
         catch (Exception)
         {
             // too flaky in windows, and this is only for testing
         }
     }));
 }
Exemplo n.º 23
0
        public void SendMessage([SelectionList("MessageTypes")] string messageType, string name)
        {
            var history = _host.Get <MessageHistory>();

            var type    = messageTypeFor(messageType);
            var message = Activator.CreateInstance(type).As <Message>();

            message.Name = name;

            var waiter = history.Watch(() => { _host.Get <IMessageContext>().Send(message).Wait(); });

            waiter.Wait(5.Seconds());

            StoryTellerAssert.Fail(!waiter.IsCompleted, "Messages were never completely tracked");
        }
        public async Task send_green_as_text_and_receive_as_blue()
        {
            greenApp = JasperHost.For <GreenApp>();
            blueApp  = JasperHost.For(new BlueApp(theTracker));


            theTracker.ShouldBeSameAs(blueApp.Get <MessageTracker>());

            var waiter = theTracker.WaitFor <BlueMessage>();

            await greenApp.Messaging
            .Send(new GreenMessage { Name = "Magic Johnson" }, _ => _.ContentType = "text/plain");

            var envelope = await waiter;


            envelope.Message
            .ShouldBeOfType <BlueMessage>()
            .Name.ShouldBe("Magic Johnson");
        }
Exemplo n.º 25
0
        //[Fact] -- unreliable. May not actually be useful.
        public async Task using_ExecuteAndWait()
        {
            await theHost.ExecuteAndWait(
                () => theHost.Messaging.Invoke(new CreateUser {
                Name = "Tom"
            }));


            using (var session = theHost.Get <IDocumentStore>().QuerySession())
            {
                session.Load <User>("Tom").ShouldNotBeNull();
            }

            theHost.Get <UserNames>()
            .Names.Single().ShouldBe("Tom");
        }
Exemplo n.º 26
0
 /// <summary>
 /// Remove any persisted incoming, scheduled, or outgoing message
 /// envelopes from your underlying database
 /// </summary>
 /// <param name="host"></param>
 public static void ClearAllPersistedMessages(this IJasperHost host)
 {
     host.Get <IEnvelopePersistence>().Admin.ClearAllPersistedEnvelopes();
 }
        protected override Envelope[] loadAllOutgoingEnvelopes(IJasperHost sender)
        {
            var admin = sender.Get <IEnvelopePersistence>().Admin;

            return(admin.AllOutgoingEnvelopes().GetAwaiter().GetResult());
        }
Exemplo n.º 28
0
 public static DurabilityAgent ForHost(IJasperHost host)
 {
     return(host.Get <JasperOptions>().DurabilityAgent);
 }
Exemplo n.º 29
0
 /// <summary>
 ///     Drops and recreates the Sql Server backed persistence database objects
 /// </summary>
 /// <param name="host"></param>
 public static void RebuildMessageStorage(this IJasperHost host)
 {
     host.Get <IEnvelopePersistence>().Admin.RebuildSchemaObjects();
 }
Exemplo n.º 30
0
        public async Task <int> PersistedScheduledCount()
        {
            var counts = await theHost.Get <IEnvelopePersistence>().Admin.GetPersistedCounts();

            return(counts.Scheduled);
        }