Ejemplo n.º 1
0
        public override void SetUp()
        {
            _transport = new StubTransport();
            _tracker   = new AttemptTracker();

            var registry = new JasperRegistry();

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

            _runtime = JasperRuntime.For(registry);

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


            _bus = _runtime.Get <IServiceBus>();
        }
Ejemplo n.º 2
0
        public async Task can_reload_the_error_report()
        {
            await theCallback.MoveToErrors(theEnvelope, new Exception("Boom!"));

            theRetries.ErrorReportLogged.WaitOne(500);


            var persistence = theRuntime.Get <MartenEnvelopePersistor>();

            var report = await persistence.LoadDeadLetterEnvelope(theEnvelope.Id);

            report.ExceptionMessage.ShouldBe("Boom!");
        }
Ejemplo n.º 3
0
        public content_negotiation()
        {
            _runtime = JasperRuntime.For(_ =>
            {
                _.Handlers.DisableConventionalDiscovery(true);
                _.Services.For <IMessageDeserializer>().Add <XmlReader <SpecialInput> >();
                _.Services.For <IMessageSerializer>().Add <XmlWriter <SpecialOutput> >();
            });

            var sourceCode = _runtime.Get <RouteGraph>().First(x => x.InputType == typeof(SpecialInput)).SourceCode;

            Console.WriteLine(sourceCode);
        }
Ejemplo n.º 4
0
        public void ForMessage([SelectionList("MessageTypes")] string MessageType)
        {
            var messageType = messageTypeFor(MessageType);

            if (_runtime == null)
            {
                _runtime = JasperRuntime.For(_registry);
            }

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

            _tracks = router.Route(messageType);
        }
Ejemplo n.º 5
0
        public override void SetUp()
        {
            _envelopes.Clear();
            _nodeLockers.Clear();

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

            _runtime = JasperRuntime.For(_ =>
            {
                _.MartenConnectionStringIs(ConnectionSource.ConnectionString);
                _.Services.AddSingleton <ITransport, StubTransport>();

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

                _.Include <MartenBackedPersistence>();

                _.Settings.Alter <MessagingSettings>(x =>
                {
                    x.FirstNodeReassignmentExecution = 30.Minutes();
                    x.FirstScheduledJobExecution     = 30.Minutes();
                    x.FirstNodeReassignmentExecution = 30.Minutes();
                    x.NodeReassignmentPollingTime    = 30.Minutes();
                });
            });

            _runtime.Get <MartenBackedDurableMessagingFactory>().ClearAllStoredMessages();

            _marker      = _runtime.Get <EnvelopeTables>();
            _serializers = _runtime.Get <MessagingSerializationGraph>();

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

            _currentNodeId = _runtime.Get <MessagingSettings>().UniqueNodeId;

            _owners["This Node"] = _currentNodeId;
        }
Ejemplo n.º 6
0
        private void remove(JasperRuntime runtime, SubscriptionsInput input)
        {
            var repository = runtime.Get <ISubscriptionsRepository>();

            Console.WriteLine($"Removing all subscriptions for service {runtime.ServiceName} to {repository}");

            repository.ReplaceSubscriptions(runtime.ServiceName, new Subscription[0])
            .Wait(1.Minutes());

            sendSubscriptionUpdates(runtime);

            ConsoleWriter.Write(ConsoleColor.Green, "Success!");
        }
        /// <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 JasperRuntime runtime, Action action,
                                                bool assertNoExceptions = false)
        {
            runtime.validateMessageTrackerExists();

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

            if (assertNoExceptions)
            {
                history.AssertNoExceptions();
            }
        }
Ejemplo n.º 8
0
        private void publish(JasperRuntime runtime)
        {
            var repository = runtime.Get <ISubscriptionsRepository>();

            Console.WriteLine($"Writing subscriptions to {repository}");

            repository.ReplaceSubscriptions(runtime.ServiceName, runtime.Capabilities.Subscriptions)
            .Wait(1.Minutes());

            sendSubscriptionUpdates(runtime);

            ConsoleWriter.Write(ConsoleColor.Green, "Success!");
        }
Ejemplo n.º 9
0
        protected void with(JasperRegistry registry)
        {
            registry.Services.Scan(_ =>
            {
                _.TheCallingAssembly();
                _.WithDefaultConventions();
            });

            Runtime = JasperRuntime.For(registry);


            Handlers = Runtime.Get <HandlerGraph>();
        }
        /// <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 JasperRuntime 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();
            }
        }
        /// <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 JasperRuntime 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();
            }
        }
Ejemplo n.º 12
0
        public void SendMessage([SelectionList("MessageTypes")] string messageType, string name)
        {
            var history = _runtime.Get <MessageHistory>();

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

            message.Name = name;

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

            waiter.Wait(5.Seconds());

            StoryTellerAssert.Fail(!waiter.IsCompleted, "Messages were never completely tracked");
        }
Ejemplo n.º 13
0
        public async Task find_all_nodes()
        {
            var node1 = new ServiceNode
            {
                Id          = "a1",
                ServiceName = "a"
            };

            var node2 = new ServiceNode
            {
                Id          = "a2",
                ServiceName = "a"
            };

            var node3 = new ServiceNode
            {
                Id          = "b1",
                ServiceName = "b"
            };

            var node4 = new ServiceNode
            {
                Id          = "c1",
                ServiceName = "c"
            };

            using (var session = _runtime.Get <IDocumentStore>().LightweightSession())
            {
                session.Store(node1, node2, node3, node4);
                await session.SaveChangesAsync();
            }

            var nodeDiscovery = _runtime.Get <INodeDiscovery>();
            var all           = await nodeDiscovery.FindAllKnown();

            // 4 + the node for the currently running app
            all.Length.ShouldBe(5);
        }
Ejemplo n.º 14
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 item2 = await loadItem(item.Id);

            if (item2 == null)
            {
                Thread.Sleep(500);
                item2 = await loadItem(item.Id);
            }



            item2.Name.ShouldBe("Shoe");


            var persistor = theReceiver.Get <SqlServerEnvelopePersistor>();

            if (persistor.AllIncomingEnvelopes().Any())
            {
                await Task.Delay(250.Milliseconds());

                persistor.AllIncomingEnvelopes().Any().ShouldBeFalse();
            }
        }
Ejemplo n.º 15
0
        protected override async Task withContext(JasperRuntime 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();
            }
        }
Ejemplo n.º 16
0
        public void Describe(JasperRuntime 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 = theRuntime.Get <MartenEnvelopePersistor>();

            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.GetPersistedCounts();

            counts.Incoming.ShouldBe(10);
            counts.Scheduled.ShouldBe(7);
            counts.Outgoing.ShouldBe(3);
        }
Ejemplo n.º 18
0
        public override void SetUp()
        {
            _envelopes.Clear();
            _nodeLockers.Clear();

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

            _runtime = JasperRuntime.For(_ =>
            {
                _.Settings.PersistMessagesWithSqlServer(Servers.SqlServerConnectionString);
                _.Services.AddSingleton <ITransport, StubTransport>();

                _.Services.AddSingleton <IWorkerQueue>(_workers);
                _.Services.AddSingleton <ISchedulingAgent>(_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();
                });
            });

            _runtime.Get <SqlServerBackedDurableMessagingFactory>().ClearAllStoredMessages();

            _serializers = _runtime.Get <MessagingSerializationGraph>();

            _runtime.RebuildMessageStorage();

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

            _owners["This Node"] = _currentNodeId;
        }
Ejemplo n.º 19
0
        protected async Task withApplication()
        {
            _runtime = await JasperRuntime.ForAsync(_ =>
            {
                _.Handlers.DisableConventionalDiscovery().IncludeType <TSagaHandler>();

                _.Include <MessageTrackingExtension>();

                _.Publish.AllMessagesTo(TransportConstants.LoopbackUri);

                configure(_);
            });

            _history = _runtime.Get <MessageHistory>();
        }
Ejemplo n.º 20
0
        public outbox_usage()
        {
            theSender   = JasperRuntime.For <ItemSender>();
            theReceiver = JasperRuntime.For <ItemReceiver>();
            theTracker  = theReceiver.Get <MessageTracker>();

            var senderStore = theSender.Get <IDocumentStore>();

            senderStore.Advanced.Clean.CompletelyRemoveAll();
            senderStore.Tenancy.Default.EnsureStorageExists(typeof(Envelope));

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

            receiverStore.Advanced.Clean.CompletelyRemoveAll();
            receiverStore.Tenancy.Default.EnsureStorageExists(typeof(Envelope));
        }
Ejemplo n.º 21
0
 public IGrammar IfTheApplicationIs()
 {
     return(Embed <ServiceBusApplication>("If a service bus application is configured to")
            .After(c =>
     {
         _runtime = c.State.Retrieve <JasperRuntime>();
         try
         {
             _runtime.Get <IDurableMessagingFactory>().ClearAllStoredMessages();
         }
         catch (Exception)
         {
             // too flaky in windows, and this is only for testing
         }
     }));
 }
Ejemplo n.º 22
0
        public async Task using_InvokeMessageAndWait()
        {
            await theRuntime.InvokeMessageAndWait(new CreateUser { Name = "Bill" });

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

            theRuntime.Get <UserNames>()
            .Names.Single().ShouldBe("Bill");
        }
Ejemplo n.º 23
0
        public ConsulNodeDiscoveryTests()
        {
            using (var client = new ConsulClient())
            {
                client.KV.DeleteTree(ConsulNodeDiscovery.TRANSPORTNODE_PREFIX).Wait();
            }

            var registry = new JasperRegistry
            {
                ServiceName = "ConsulTestApp"
            };

            registry.Services.ForSingletonOf <INodeDiscovery>().Use <ConsulNodeDiscovery>();

            _runtime = JasperRuntime.For(registry);

            theNodeDiscovery = _runtime.Get <INodeDiscovery>().As <ConsulNodeDiscovery>();
        }
        public ConsulSubscriptionRepositoryTests()
        {
            using (var client = new ConsulClient())
            {
                client.KV.DeleteTree(ConsulSubscriptionRepository.SUBSCRIPTION_PREFIX).Wait();
            }

            var registry = new JasperRegistry();

            registry.ServiceName = "ConsulSampleApp";

            registry.Services.For <ISubscriptionsRepository>()
            .Use <ConsulSubscriptionRepository>();

            _runtime = JasperRuntime.For(registry);

            theRepository = _runtime.Get <ISubscriptionsRepository>();
        }
        public subscription_repository_functionality()
        {
            using (var store = DocumentStore.For(ConnectionSource.ConnectionString))
            {
                store.Advanced.Clean.CompletelyRemoveAll();
            }

            _runtime = JasperRuntime.For(_ =>
            {
                _.Settings.Alter <MartenSubscriptionSettings>(x => x.StoreOptions.Connection(ConnectionSource.ConnectionString));

                _.Include <MartenBackedSubscriptions>();

                _.ServiceName = "MartenSampleApp";
            });



            theRepository = _runtime.Get <ISubscriptionsRepository>();
        }
Ejemplo n.º 26
0
        public async Task send_green_as_text_and_receive_as_blue()
        {
            greenApp = await JasperRuntime.ForAsync <GreenApp>();

            blueApp = await JasperRuntime.ForAsync(new BlueApp(theTracker));


            theTracker.ShouldBeTheSameAs(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");
        }
Ejemplo n.º 27
0
        //[Fact] -- unreliable. May not actually be useful.
        public async Task using_ExecuteAndWait()
        {
            await theRuntime.ExecuteAndWait(
                () => { return(theRuntime.Messaging.Invoke(new CreateUser {
                    Name = "Tom"
                })); });


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

            theRuntime.Get <UserNames>()
            .Names.Single().ShouldBe("Tom");
        }
Ejemplo n.º 28
0
        public MartenCallbackTests()
        {
            theRuntime = JasperRuntime.For(_ =>
            {
                _.MartenConnectionStringIs(ConnectionSource.ConnectionString);

                _.ConfigureMarten(x =>
                {
                    x.Storage.Add <PostgresqlEnvelopeStorage>();
                    x.PLV8Enabled = false;
                });
            });

            theStore = theRuntime.Get <IDocumentStore>();

            theStore.Advanced.Clean.CompletelyRemoveAll();
            theStore.Schema.ApplyAllConfiguredChangesToDatabase();

            theEnvelope        = ObjectMother.Envelope();
            theEnvelope.Status = TransportConstants.Incoming;

            var marker = new EnvelopeTables(new MessagingSettings(), new StoreOptions());

            using (var session = theStore.OpenSession())
            {
                session.StoreIncoming(marker, theEnvelope);
                session.SaveChanges();
            }


            var logger = TransportLogger.Empty();

            theRetries = new EnvelopeRetries(new MartenEnvelopePersistor(theStore, marker), logger, new MessagingSettings());


            var persistor = new MartenEnvelopePersistor(theStore, marker);

            theCallback = new DurableCallback(theEnvelope, Substitute.For <IWorkerQueue>(), persistor, theRetries, logger);
        }
Ejemplo n.º 29
0
        public T FromJson <T>(string json)
        {
            var graph = _runtime.Get <HttpSerializationGraph>();

            return((T)graph.JsonReaderFor(typeof(T)).ReadFromData(Encoding.Default.GetBytes(json)));
        }
        public static JasperRuntime DefaultRegistrationIs <T>(this JasperRuntime runtime, T value) where T : class
        {
            runtime.Get <T>().ShouldBeSameAs(value);

            return(runtime);
        }