public StoreTimeoutBehavior(ExpiredTimeoutsPoller poller, IDispatchMessages dispatcher, IPersistTimeouts persister, string owningTimeoutManager) { this.poller = poller; this.dispatcher = dispatcher; this.persister = persister; this.owningTimeoutManager = owningTimeoutManager; }
async Task OnMessage(MessageContext context, IDispatchMessages dispatcher, Task <bool> barrier, ICollection <string> ownCatalogs) { //Ensure all endpoinst are created. await barrier.ConfigureAwait(false); string destination; if (!context.Headers.TryGetValue("NServiceBus.SqlServer.Destination", out destination)) { throw new Exception("No destination header present."); } context.Headers.Remove("NServiceBus.SqlServer.Destination"); var address = QueueAddress.Parse(destination); var outgoingMessage = new OutgoingMessage(context.MessageId, context.Headers, context.Body); var operation = new TransportOperation(outgoingMessage, new UnicastAddressTag(destination)); var operations = new TransportOperations(operation); if (ownCatalogs.Contains(address.Catalog)) //Forward to the same instance on the receiving connection/transaction { await dispatcher.Dispatch(operations, context.TransportTransaction, context.Context).ConfigureAwait(false); } else //Forward to different instance { IRawEndpointInstance forwarder; if (!endpointsByCatalog.TryGetValue(address.Catalog, out forwarder)) { throw new Exception($"Destination catalog {address.Catalog} is not configured."); } await forwarder.SendRaw(operations, new TransportTransaction(), new ContextBag()).ConfigureAwait(false); } }
static async Task Send(IDispatchMessages dispatchMessages, int messageNumber) { try { if (!concurrencyLimiter.Wait(0)) { await concurrencyLimiter.WaitAsync(); } var headers = new Dictionary <string, string>(reusedHeaders); var messageId = Guid.NewGuid().ToString(); headers[Headers.MessageId] = messageId; headers[Headers.CorrelationId] = messageId; headers[Headers.ConversationId] = Guid.NewGuid().ToString(); headers[Headers.MessageIntent] = "Send"; headers[Headers.TimeSent] = DateTimeExtensions.ToWireFormattedString(DateTime.UtcNow); ExceptionHeaderHelper.SetExceptionHeaders(headers, exceptions[messageNumber % 3]); var message = new OutgoingMessage(messageId, headers, content); var operation = new TransportOperation(message, new UnicastAddressTag("error")); await dispatchMessages.Dispatch(new TransportOperations(operation), transportTransaction, contextBag); // no overwhelm with too much output if (messageNumber % 1000 == 0) { await Console.Error.WriteLineAsync($"|{messageNumber}|"); } } finally { concurrencyLimiter.Release(); } }
public ReadyMessageSender(IDispatchMessages dispatcher, string receiveAddress, int initialCapacity, string distributorControlAddress) { this.initialCapacity = initialCapacity; this.distributorControlAddress = distributorControlAddress; this.dispatcher = dispatcher; this.receiveAddress = receiveAddress; }
public static Task Send(this IDispatchMessages endpoint, Message message, Guid?runId = null) { runId ??= Guid.NewGuid(); var headers = new Dictionary <string, string> { { "Message.Id", message.Id.ToString() }, { "Message.RunId", runId.ToString() } }; var body = Serializer.Serialize(message, headers); var request = new OutgoingMessage( messageId: Guid.NewGuid().ToString(), headers: headers, body: body); var operation = new TransportOperation( request, new UnicastAddressTag(EndpointBuilder.EndpointName)); return(endpoint.Dispatch( outgoingMessages: new TransportOperations(operation), transaction: new TransportTransaction(), context: new ContextBag())); }
public async Task SendToDestination(MessageContext context, IDispatchMessages dispatcher, SingleCallChannelForwarder forwarder) { var intent = GetMessageIntent(context.Headers); var destinationSites = GetDestinationSitesFor(context.Headers, intent); //if there is more than 1 destination we break it up into multiple dispatches if (destinationSites.Count > 1) { foreach (var destinationSite in destinationSites) { await CloneAndSendLocal(context.Body, context.Headers, destinationSite, context.TransportTransaction, dispatcher).ConfigureAwait(false); } return; } var destination = destinationSites.FirstOrDefault(); if (destination == null) { throw new InvalidOperationException("No destination found for message"); } await SendToSite(context.Body, context.Headers, destination, forwarder).ConfigureAwait(false); }
public ISagaManager Create(Func <string, Task> barrierCallback, IDispatchMessages dispatcher) { return(new SagaManager( new TestingSagaDataPersister(barrierCallback, persister), new TestingOutbox(barrierCallback, outbox), dispatcher)); }
public CustomChecksStartup(IEnumerable<ICustomCheck> customChecks, ReadOnlySettings settings, CriticalError criticalError, IDispatchMessages dispatcher) { dispatchMessages = dispatcher; this.criticalError = criticalError; this.settings = settings; this.customChecks = customChecks.ToList(); }
public SagaManagerTask(ISagaManagerFactory managerFactory, IDispatchMessages dispatcher, string messageId, string sagaId, string processId) { this.manager = managerFactory.Create(GetBarrier, dispatcher); this.messageId = messageId; this.sagaId = sagaId; this.processId = processId; }
public HeartbeatStartup(IDispatchMessages messageDispatcher, ReadOnlySettings settings) { backend = new ServiceControlBackend(messageDispatcher, settings); endpointName = settings.EndpointName(); HostId = settings.Get<Guid>("NServiceBus.HostInformation.HostId"); Host = settings.Get<string>("NServiceBus.HostInformation.DisplayName"); Properties = settings.Get<Dictionary<string, string>>("NServiceBus.HostInformation.Properties"); var interval = ConfigurationManager.AppSettings["Heartbeat/Interval"]; if (!string.IsNullOrEmpty(interval)) { heartbeatInterval = TimeSpan.Parse(interval); } else if (settings.HasSetting("ServiceControl.Heartbeat.Interval")) { heartbeatInterval = settings.Get<TimeSpan>("ServiceControl.Heartbeat.Interval"); } ttlTimeSpan = TimeSpan.FromTicks(heartbeatInterval.Ticks*4); // Default ttl var ttl = ConfigurationManager.AppSettings["Heartbeat/TTL"]; if (!string.IsNullOrEmpty(ttl)) { ttlTimeSpan = TimeSpan.Parse(ttl); } else if (settings.HasSetting("ServiceControl.Heartbeat.Ttl")) { ttlTimeSpan = settings.Get<TimeSpan>("ServiceControl.Heartbeat.Ttl"); } }
public CustomChecksStartup(IEnumerable <ICustomCheck> customChecks, ReadOnlySettings settings, CriticalError criticalError, IDispatchMessages dispatcher) { dispatchMessages = dispatcher; this.criticalError = criticalError; this.settings = settings; this.customChecks = customChecks.ToList(); }
public static Task OnMessage(MessageContext context, IDispatchMessages dispatcher) { try { var fromAddress = new MailAddress("*****@*****.**", "Subscriber2"); var toAddress = new MailAddress("*****@*****.**", "To Admin"); var message = BusStuff.Deserialize(context.Body); subject = message.OperationType; body = message.ToString(); var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var msg = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(msg); BusStuff.LogCall("Emailed: " + msg.Body); } return(Task.CompletedTask); } catch (Exception e) { BusStuff.LogCall(e.Message + Environment.NewLine + "Failed for " + subject + " : " + body); return(Task.CompletedTask); } }
public OutboxBehavior(Repository <T> repository, IDispatchMessages dispatcher, ITokenStore tokenStore, Func <object, string> getId) { this.repository = repository; this.dispatcher = dispatcher; this.tokenStore = tokenStore; this.getId = getId; }
public async Task Publish(MessageContext context, IDispatchMessages dispatcher) { var messageTypes = Get(context, Headers.EnclosedMessageTypes, "Publish") .Split(EnclosedMessageTypeSeparator) .Select(t => new MessageType(t)); var subscribers = await store.GetSubscriberAddressesForMessage(messageTypes, context.Extensions); var logicalSubscribers = subscribers.GroupBy(s => s.Endpoint, s => s.TransportAddress); var destinations = logicalSubscribers.Select(subscriber => distributor.SelectDestination(subscriber.Key, subscriber.ToArray(), context)); var operations = destinations.Select(destination => new TransportOperation( new OutgoingMessage(context.MessageId, context.Headers, context.Body), new UnicastAddressTag(destination))).ToArray(); if (!operations.Any()) { // Log that we didn't dispatch anything return; } await dispatcher.Dispatch(new TransportOperations(operations), context.TransportTransaction, context.Extensions); }
public virtual async Task HandleMessage(MessageContext message, IDispatchMessages sender) { var body = new byte[0]; var outgoingHeaders = new Dictionary <string, string>(message.Headers); outgoingHeaders.Remove("ServiceControl.Retry.StagingId"); var messageId = message.MessageId; Log.DebugFormat("{0}: Retrieving message body", messageId); if (outgoingHeaders.TryGetValue("ServiceControl.Retry.Attempt.MessageId", out var attemptMessageId)) { var result = await bodyStorage.TryFetch(attemptMessageId) .ConfigureAwait(false); if (result.HasResult) { using (result.Stream) { body = ReadFully(result.Stream); } Log.DebugFormat("{0}: Body size: {1} bytes", messageId, body.LongLength); } else { Log.WarnFormat("{0}: Message Body not found for attempt Id {1}", messageId, attemptMessageId); } outgoingHeaders.Remove("ServiceControl.Retry.Attempt.MessageId"); } else { Log.WarnFormat("{0}: Can't find message body. Missing header ServiceControl.Retry.Attempt.MessageId", messageId); } var outgoingMessage = new OutgoingMessage(messageId, outgoingHeaders, body); var destination = outgoingHeaders["ServiceControl.TargetEndpointAddress"]; Log.DebugFormat("{0}: Forwarding message to {1}", messageId, destination); if (!outgoingHeaders.TryGetValue("ServiceControl.RetryTo", out var retryTo)) { retryTo = destination; outgoingHeaders.Remove("ServiceControl.TargetEndpointAddress"); } else { Log.DebugFormat("{0}: Found ServiceControl.RetryTo header. Rerouting to {1}", messageId, retryTo); } var transportOp = new TransportOperation(outgoingMessage, new UnicastAddressTag(retryTo)); await sender.Dispatch(new TransportOperations(transportOp), message.TransportTransaction, message.Extensions) .ConfigureAwait(false); Log.DebugFormat("{0}: Forwarded message to {1}", messageId, retryTo); }
public async Task Initialize(IDispatchMessages dispatcher) { this.dispatcher = dispatcher; if (settings.ForwardAuditMessages) { await VerifyCanReachForwardingAddress().ConfigureAwait(false); } }
public ISagaManager Create(Func <string, Task> barrierCallback, IDispatchMessages dispatcher) { return(new SagaManager( new TestingSagaDataPersister(barrierCallback, persister), new TestingTokenStore(barrierCallback, tokenStore), new TestingOutbox(barrierCallback, outbox), transientMessageStateStore, dispatcher)); }
public DispatchTask(IDispatchMessages dispatcher, Func <TransportOperations> operationFactory, Func <IMessageSession, Task> before, Func <IMessageSession, Task> after, ScenarioContext scenarioContext) { this.after = after; this.scenarioContext = scenarioContext; this.before = before; this.operationFactory = operationFactory; dispatchMessages = dispatcher; }
public RetryProcessor(IDispatchMessages sender, IDomainEvents domainEvents, ReturnToSenderDequeuer returnToSender, RetryingManager retryingManager) { this.sender = sender; this.returnToSender = returnToSender; this.retryingManager = retryingManager; this.domainEvents = domainEvents; corruptedReplyToHeaderStrategy = new CorruptedReplyToHeaderStrategy(RuntimeEnvironment.MachineName); }
public OutboxBehavior(Repository <T> repository, IDispatchMessages dispatcher, IInboxStore inboxStore, IOutboxStore outboxStore, Func <object, string> getId) { this.repository = repository; this.dispatcher = dispatcher; this.inboxStore = inboxStore; this.getId = getId; this.outboxStore = outboxStore; }
public SagaManager(ISagaPersister sagaPersister, ITokenStore tokenStore, IOutboxStore outboxStore, ITransientMessageStateStore transientMessageStateStore, IDispatchMessages dispatcher) { this.sagaPersister = sagaPersister; this.tokenStore = tokenStore; this.dispatcher = dispatcher; this.outboxStore = outboxStore; this.transientMessageStateStore = transientMessageStateStore; }
static Task OnMessage(MessageContext context, IDispatchMessages dispatcher) { var message = Deserialize(context.Body); Console.WriteLine(message); // Can use dispatcher to send messages from here return(Task.CompletedTask); }
public override Task HandleMessage(MessageContext message, IDispatchMessages sender) { if (message.Headers[Headers.MessageId] == myContext.DecommissionedEndpointMessageId) { throw new Exception("This endpoint is unreachable"); } return(base.HandleMessage(message, sender)); }
public GatewayReceiverStartupTask(IManageReceiveChannels channelManager, Func <string, IChannelReceiver> channelReceiverFactory, EndpointRouter endpointRouter, IDispatchMessages dispatcher, IDeduplicateMessages deduplicator, IDataBus databus, string replyToAddress) { dispatchMessages = dispatcher; this.deduplicator = deduplicator; this.databus = databus; this.endpointRouter = endpointRouter; manageReceiveChannels = channelManager; this.channelReceiverFactory = channelReceiverFactory; this.replyToAddress = replyToAddress; }
public RawTransportReceiver(IPushMessages pushMessages, IDispatchMessages dispatcher, Func <MessageContext, IDispatchMessages, Task> onMessage, PushSettings pushSettings, PushRuntimeSettings pushRuntimeSettings, CriticalError criticalError, RawEndpointErrorHandlingPolicy errorHandlingPolicy) { this.criticalError = criticalError; this.errorHandlingPolicy = errorHandlingPolicy; this.pushRuntimeSettings = pushRuntimeSettings; this.pushSettings = pushSettings; receiver = pushMessages; this.onMessage = context => onMessage(context, dispatcher); }
private static async Task OnMessage(MessageContext context, IDispatchMessages dispatcher, Channel <MessageContext> channel) { var tcs = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously); context.Extensions.Set(tcs); await channel.Writer.WriteAsync(context); await tcs.Task; }
public BaseSagaTests() { // LogManager.OutputToTrace(); _invoker = Substitute.For <IHandlerTypeInvoker>(); _di = Substitute.For <IContainerScope>(); _bus = Substitute.For <IDispatchMessages>(); _handler = new Handler(_bus); _storage = Substitute.For <IStoreSagaState>(); _saga = new MySagaState(); this.Setup(); }
public MessageStreamerConnection(IDispatchMessages sender, ReadOnlySettings settings) { var conventions = settings.Get <Conventions>(); this.sender = sender; messageTypes = settings.GetAvailableTypes() .Where(conventions.IsMessageType) .GroupBy(x => x.Name) .ToDictionary(x => x.Key, x => x.FirstOrDefault().AssemblyQualifiedName); localAddress = settings.LocalAddress(); }
public Task OnMessage(MessageContext context, IDispatchMessages dispatcher) { var metricsData = Deserialize <JsonMetricsContext>(context); receivedMetricContext.Consume(metricsData.ToMetricsData()); foreach (var metric in derivedMetrics) { metric.Consume(metricsData); } return(Task.CompletedTask); }
public static Task OnMessage(MessageContext context, IDispatchMessages dispatcher) { try { var b = context.Body; var message = BusStuff.Deserialize(context.Body); operation = message.OperationType; body = message.ToString(); switch (message.OperationType) { case "Create": { using (TransactionScope sc = new TransactionScope(TransactionScopeOption.Suppress)) { unit.Books.Create(message.body); unit.Save(); messagesQueue.Add(message); } break; } case "Delete": { using (TransactionScope sc = new TransactionScope(TransactionScopeOption.Suppress)) { unit.Books.Delete(message.body.Id); unit.Save(); messagesQueue.Add(message); } break; } case "Update": { using (TransactionScope sc = new TransactionScope(TransactionScopeOption.Suppress)) { unit.Books.Update(message.body); unit.Save(); messagesQueue.Add(message); } break; } } return(Task.CompletedTask); } catch (Exception er) { MessageBox.Show(er.Message); BusStuff.LogCall("Operation " + operation + " for " + body + " failed"); return(Task.CompletedTask); } }
Task OnMessage(MessageContext messageContext, IDispatchMessages dispatcher) { if (Interlocked.CompareExchange(ref failureDetected, 1, 0) == 0) { if (messageContext.Headers.TryGetValue("NServiceBus.ExceptionInfo.Message", out var exceptionMessage)) { scenarioContext.ExceptionMessage = exceptionMessage; } scenarioContext.PoisonMessageDetected = true; } return(Task.CompletedTask); }
public ExpiredTimeoutsPoller(IQueryTimeouts timeoutsFetcher, IDispatchMessages dispatcher, string dispatcherAddress, ICircuitBreaker circuitBreaker, Func<DateTime> currentTimeProvider) { this.timeoutsFetcher = timeoutsFetcher; this.dispatcher = dispatcher; this.dispatcherAddress = dispatcherAddress; this.circuitBreaker = circuitBreaker; this.currentTimeProvider = currentTimeProvider; var now = currentTimeProvider(); startSlice = now.AddYears(-10); NextRetrieval = now; }
public ExpiredTimeoutsPoller(IQueryTimeouts timeoutsFetcher, IDispatchMessages dispatcher, string dispatcherAddress, ICircuitBreaker circuitBreaker, Func <DateTime> currentTimeProvider) { this.timeoutsFetcher = timeoutsFetcher; this.dispatcher = dispatcher; this.dispatcherAddress = dispatcherAddress; this.circuitBreaker = circuitBreaker; this.currentTimeProvider = currentTimeProvider; var now = currentTimeProvider(); startSlice = now.AddYears(-10); NextRetrieval = now; }
public BaseSagaTests() { LogManager.OutputToTrace(); _invoker = Substitute.For<IHandlerTypeInvoker>(); _di = Substitute.For<IContainerScope>(); _bus = Substitute.For<IDispatchMessages>(); _handler = new Handler(_bus); _storage = Substitute.For<IStoreSagaState>(); _saga = new MySagaState(); this.Setup(); }
public ServiceControlBackend(IDispatchMessages messageSender, ReadOnlySettings settings, CriticalError criticalError) { this.settings = settings; this.messageSender = messageSender; serializer = new DataContractJsonSerializer(typeof(ReportCustomCheckResult), new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat("o"), EmitTypeInformation = EmitTypeInformation.Always, }); serviceControlBackendAddress = GetServiceControlAddress(); circuitBreaker = new RepeatedFailuresOverTimeCircuitBreaker("ServiceControlConnectivity", TimeSpan.FromMinutes(2), ex => criticalError.Raise("You have ServiceControl plugins installed in your endpoint, however, this endpoint is repeatedly unable to contact the ServiceControl backend to report endpoint information.", ex)); }
async Task RawSending(IDispatchMessages dispatcher) { #region DispatcherRawSending Dictionary<string, string> headers = new Dictionary<string, string>(); OutgoingMessage outgoingMessage = new OutgoingMessage("MessageId", headers, new byte[] { }); NonDurableDelivery[] constraints = { new NonDurableDelivery() }; UnicastAddressTag address = new UnicastAddressTag("Destination"); TransportOperation transportOperation = new TransportOperation(outgoingMessage, address, DispatchConsistency.Default, constraints); TransportOperations operations = new TransportOperations(transportOperation); await dispatcher.Dispatch(operations, new ContextBag()); #endregion }
public ServiceControlBackend(IDispatchMessages messageSender, ReadOnlySettings settings) { this.settings = settings; this.messageSender = messageSender; startupSerializer = new DataContractJsonSerializer(typeof(RegisterEndpointStartup), new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat("o"), EmitTypeInformation = EmitTypeInformation.Never, UseSimpleDictionaryFormat = true }); heartbeatSerializer = new DataContractJsonSerializer(typeof(EndpointHeartbeat), new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat("o"), EmitTypeInformation = EmitTypeInformation.Never, UseSimpleDictionaryFormat = true }); serviceControlBackendAddress = GetServiceControlAddress(); }
/// <summary> /// Publishes and clears events /// </summary> /// <param name="entity"></param> /// <param name="bus"></param> public static void PublishEvents(this IGenerateEvents entity,IDispatchMessages bus) { entity.MustNotBeNull(); bus.Publish(entity.GetGeneratedEvents()); entity.ClearEvents(); }
public DispatchTimeoutBehavior(IDispatchMessages dispatcher, IPersistTimeouts persister, TransportTransactionMode transportTransactionMode) { this.dispatcher = dispatcher; this.persister = persister; dispatchConsistency = GetDispatchConsistency(transportTransactionMode); }
public DelayedRetryExecutor(string endpointInputQueue, IDispatchMessages dispatcher, string timeoutManagerAddress = null) { this.timeoutManagerAddress = timeoutManagerAddress; this.dispatcher = dispatcher; this.endpointInputQueue = endpointInputQueue; }
public IdempotentUnitOfWork(IStoreMessages storage, IDispatchMessages dispatcher, IBuildMessages builder) { this.storage = storage; this.dispatcher = dispatcher; this.builder = builder; }
public DuplicateMessageFilter(ILoadMessages repository, IDispatchMessages dispatcher) { this.messageLoad = repository; this.dispatcher = dispatcher; }
public MoveToErrorsExecutor(IDispatchMessages dispatcher, Dictionary<string, string> staticFaultMetadata, Action<Dictionary<string, string>> headerCustomizations) { this.dispatcher = dispatcher; this.staticFaultMetadata = staticFaultMetadata; this.headerCustomizations = headerCustomizations; }