public static void AddProducer(this MessagingOptions builder, Action <ProducerConfig> configuration) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } var config = new ProducerConfig(); configuration(config); if (config.ProducerConfiguration == null) { throw new ArgumentNullException(nameof(config.ProducerConfiguration)); } builder.Container.Register(typeof(IEnumerable <MessageConfiguration>), () => config.MessageConfigurations.Select(a => { var c = new MessageConfiguration(); c.Init(a); return(c); }), Lifestyle.Singleton); builder.Container.Register(typeof(IMessageConfigurationProvider <>), typeof(MessageConfigurationProvider <>), Lifestyle.Singleton); builder.Container.RegisterSingleton <IProducerFactory, ProducerFactory>(); builder.Container.RegisterSingleton <IProducerConfiguration>(config); builder.HasProducer = true; }
public InMemoryMessageBroker(IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher, MessagingOptions messagingOptions) { _moduleClient = moduleClient; _asyncMessageDispatcher = asyncMessageDispatcher; _messagingOptions = messagingOptions; }
public static MessagingOptions UseRabbitMQBroker( this MessagingOptions options, Action <IMessageBroker> brokerAction = null, string section = "naos:messaging:rabbitMQ", IEnumerable <Assembly> assemblies = null) { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); options.Context.Services.AddSingleton <IMessageBroker>(sp => { var rabbitMQConfiguration = options.Context.Configuration.GetSection(section).Get <RabbitMQConfiguration>(); var broker = new RabbitMQMessageBroker(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Host(rabbitMQConfiguration.Host) .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp))); brokerAction?.Invoke(broker); return(broker); }); options.Context.Messages.Add($"{LogKeys.Startup} naos services builder: messaging added (broker={nameof(RabbitMQMessageBroker)})"); return(options); }
} // might hold metadata used by response pipeline public CallbackData( Action <Message, TaskCompletionSource <object> > callback, Func <Message, bool> resendFunc, TaskCompletionSource <object> ctx, Message msg, Action <Message> unregisterDelegate, MessagingOptions messagingOptions, ILogger logger, ILogger timerLogger) { // We are never called without a callback func, but best to double check. if (callback == null) { throw new ArgumentNullException(nameof(callback)); } // We are never called without a resend func, but best to double check. if (resendFunc == null) { throw new ArgumentNullException(nameof(resendFunc)); } this.logger = logger; this.callback = callback; this.resendFunc = resendFunc; context = ctx; Message = msg; unregister = unregisterDelegate; alreadyFired = false; this.messagingOptions = messagingOptions; this.TransactionInfo = TransactionContext.GetTransactionInfo(); this.timerLogger = timerLogger; }
public void Constructor_Initialises_Correctly() { var target = new MessagingOptions(); Assert.Null(target.Url); Assert.False(target.HasUrl); }
public static MessagingOptions UseSignalRBroker( this MessagingOptions options, Action <IMessageBroker> brokerAction = null, string messageScope = null, string section = "naos:messaging:signalr") { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); options.Context.Services.AddSingleton <IMessageBroker>(sp => { var configuration = options.Context.Configuration.GetSection(section).Get <SignalRConfiguration>(); var broker = new SignalRServerlessMessageBroker(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator((IMediator)sp.CreateScope().ServiceProvider.GetService(typeof(IMediator))) .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp)) .ConnectionString(configuration.ConnectionString) .HttpClient(sp.GetRequiredService <IHttpClientFactory>()) .Map(sp.GetRequiredService <ISubscriptionMap>()) .FilterScope(Environment.GetEnvironmentVariable(EnvironmentKeys.IsLocal).ToBool() ? Environment.MachineName.Humanize().Dehumanize().ToLower() : string.Empty) .MessageScope(messageScope)); brokerAction?.Invoke(broker); return(broker); }); options.Context.Messages.Add($"{LogEventKeys.Startup} naos services builder: messaging added (broker={nameof(SignalRServerlessMessageBroker)})"); return(options); }
public BaseKafkaProducer(IOptions <MessagingOptions> options, ILogger <BaseKafkaProducer <TMessage> > logger) { _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _logger = logger; _producer = GetProducer(); }
/// <summary> /// Initializes a new instance of the <see cref="AccountController" /> /// class. /// </summary> /// <param name="userManager">The user manager.</param> /// <param name="messageBuilder">The message builder.</param> /// <param name="mailer">The mailer.</param> /// <param name="options">The options.</param> /// <param name="logger">The logger.</param> /// <exception cref="ArgumentNullException">null options or userManager or /// signInManager or environment or messageBuilder or mailer</exception> public AccountController(UserManager <ApplicationUser> userManager, IMessageBuilderService messageBuilder, IMailerService mailer, IOptions <MessagingOptions> options, ILogger <AccountController> logger) { if (options == null) { throw new ArgumentNullException(nameof(options)); } _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); //_signInManager = signInManager ?? // throw new ArgumentNullException(nameof(signInManager)); //_environment = environment ?? // throw new ArgumentNullException(nameof(environment)); _messageBuilder = messageBuilder ?? throw new ArgumentNullException(nameof(messageBuilder)); _mailer = mailer ?? throw new ArgumentNullException(nameof(mailer)); _options = options.Value; //_configuration = configuration ?? // throw new ArgumentNullException(nameof(configuration)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
//============================================================================================= Static API public static SecuritySystem StartSecurity(ISecurityDataProvider securityDataProvider, IMessageProvider messageProvider, IMissingEntityHandler missingEntityHandler, MessagingOptions messagingOptions) { var securityConfig = new SecurityConfiguration { SystemUserId = Identifiers.SystemUserId, VisitorUserId = Identifiers.VisitorUserId, EveryoneGroupId = Identifiers.EveryoneGroupId, OwnerGroupId = Identifiers.OwnersGroupId }; var securitySystem = new SecuritySystem(securityDataProvider, messageProvider, missingEntityHandler, securityConfig, messagingOptions); securitySystem.Start(); SnLog.WriteInformation("Security subsystem started in Search service", EventId.RepositoryLifecycle, properties: new Dictionary <string, object> { { "DataProvider", securityDataProvider.GetType().FullName }, { "MessageProvider", messageProvider.GetType().FullName } }); return(securitySystem); }
internal static SecuritySystem StartTheSystem(ISecurityDataProvider securityDataProvider) { var messageSenderManager = new MessageSenderManager("asdf"); // Call SecurityContext starter method. //var securitySystem = SecurityContextForConcurrencyTests.StartTheSystem(new SecurityConfiguration //{ // SecurityDataProvider = securityDataProvider, // MessageProvider = new DefaultMessageProvider(messageSenderManager), // CommunicationMonitorRunningPeriodInSeconds = 31 //}); var config = new SecurityConfiguration(); var messagingOptions = new MessagingOptions { CommunicationMonitorRunningPeriodInSeconds = 31 }; var securitySystem = new SecuritySystem(securityDataProvider, new DefaultMessageProvider(messageSenderManager), new MissingEntityHandler(), config, messagingOptions); securitySystem.Start(); // legacy logic // original line: MessageSender.Initialize("asdf"); //securitySystem.MessageSenderManager = messageSenderManager; return(securitySystem); }
public MessageBroker(IModuleClient moduleClient, IBusPublisher busPublisher, IAsyncMessageDispatcher asyncMessageDispatcher, MessagingOptions messagingOptions) { _moduleClient = moduleClient; _busPublisher = busPublisher; _asyncMessageDispatcher = asyncMessageDispatcher; _messagingOptions = messagingOptions; }
/// <summary> /// Initializes a new instance of the <see cref="Invocation"/> class. /// </summary> /// <param name="requestMessage">The request message.</param> /// <param name="messagingOptions">Messaging options.</param> /// <param name="partitionId">The identifier of the target partition.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <remarks> /// <para>If the target partition cannot be mapped to an available member, another random member will be used.</para> /// </remarks> public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions, int partitionId, CancellationToken cancellationToken) : this(requestMessage, messagingOptions, cancellationToken) { if (partitionId < 0) { throw new ArgumentException("Must be a positive integer.", nameof(partitionId)); } TargetPartitionId = partitionId; }
/// <summary> /// Initializes a new instance of the <see cref="Invocation"/> class. /// </summary> /// <param name="requestMessage">The request message.</param> /// <param name="messagingOptions">Messaging options.</param> /// <param name="targetMemberId">The identifier of the target member.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <remarks> /// <para>If the target member is not available, another random member will be used.</para> /// </remarks> public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions, Guid targetMemberId, CancellationToken cancellationToken) : this(requestMessage, messagingOptions, cancellationToken) { if (targetMemberId == default) { throw new ArgumentException("Must be a non-default Guid.", nameof(targetMemberId)); } TargetMemberId = targetMemberId; }
/// <summary> /// Initializes a new instance of the <see cref="FileMessageBuilderService"/> /// class. /// </summary> /// <param name="environment">The environment.</param> /// <param name="options">The options.</param> public FileMessageBuilderService(MessagingOptions options, IHostEnvironment environment) : base(options) { // http://stackoverflow.com/questions/35842547/read-solution-data-files-asp-net-core/35863315 _messageDir = Path.Combine( environment.ContentRootPath, "wwwroot", "messages") + Path.DirectorySeparatorChar; }
private int _attemptsCount; // number of times this invocation has been attempted /// <summary> /// Initializes a new instance of the <see cref="Invocation"/> class. /// </summary> /// <param name="requestMessage">The request message.</param> /// <param name="messagingOptions">Messaging options.</param> public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions) { RequestMessage = requestMessage ?? throw new ArgumentNullException(nameof(requestMessage)); _messagingOptions = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions)); CorrelationId = requestMessage.CorrelationId; InitializeNewCompletionSource(); _attemptsCount = 1; StartTime = Clock.Milliseconds; }
public InMemoryMessageBroker(IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher, IContext context, IOutbox outbox, MessagingOptions messagingOptions, ILogger <InMemoryMessageBroker> logger) { _moduleClient = moduleClient; _asyncMessageDispatcher = asyncMessageDispatcher; _context = context; _outbox = outbox; _messagingOptions = messagingOptions; _logger = logger; }
public EventPublisher(MessagingOptions options) { var factory = new ConnectionFactory() { Uri = new Uri(options.ConnectionString) }; _connection = factory.CreateConnection(); _channel = _connection.CreateModel(); }
public SendMessageService( IMapper mapper, IOptions <MessagingOptions> messagingOptions) { _messagingOptions = messagingOptions.Value; _mapper = mapper; topicClient = new TopicClient( _messagingOptions.ServiceBusConnectionString, _messagingOptions.TopicNameToSend); }
private int _attemptsCount; // number of times this invocation has been attempted /// <summary> /// Initializes a new instance of the <see cref="Invocation"/> class. /// </summary> /// <param name="requestMessage">The request message.</param> /// <param name="messagingOptions">Messaging options.</param> /// <param name="cancellationToken">A cancellation token.</param> public Invocation(ClientMessage requestMessage, MessagingOptions messagingOptions, CancellationToken cancellationToken) { RequestMessage = requestMessage ?? throw new ArgumentNullException(nameof(requestMessage)); _messagingOptions = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions)); CorrelationId = requestMessage.CorrelationId; _cancellationToken = cancellationToken; InitializeNewCompletionSource(); _registration = _cancellationToken.Register(TrySetCanceled); // must dispose to de-register! _attemptsCount = 1; StartTime = Clock.Milliseconds; }
public SharedCallbackData( Action <Message> unregister, ILogger logger, MessagingOptions messagingOptions, ApplicationRequestsStatisticsGroup requestStatistics) { RequestStatistics = requestStatistics; this.Unregister = unregister; this.Logger = logger; this.MessagingOptions = messagingOptions; this.ResponseTimeout = messagingOptions.ResponseTimeout; }
public EventSubscriber(MessagingOptions options, IMediator mediator, ILogger <EventSubscriber> logger) { _mediator = mediator; _logger = logger; var factory = new ConnectionFactory { Uri = new Uri(options.ConnectionString) }; _connection = factory.CreateConnection(); _channel = _connection.CreateModel(); }
/// <summary> /// Initializes a new instance of the <see cref="MemberConnection"/> class. /// </summary> /// <param name="address">The network address.</param> /// <param name="authenticator">The authenticator.</param> /// <param name="messagingOptions">Messaging options.</param> /// <param name="networkingOptions">Networking options.</param> /// <param name="sslOptions">SSL options.</param> /// <param name="correlationIdSequence">A sequence of unique correlation identifiers.</param> /// <param name="loggerFactory">A logger factory.</param> public MemberConnection(NetworkAddress address, Authenticator authenticator, MessagingOptions messagingOptions, NetworkingOptions networkingOptions, SslOptions sslOptions, ISequence <long> correlationIdSequence, ILoggerFactory loggerFactory) { Address = address ?? throw new ArgumentNullException(nameof(address)); _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); _messagingOptions = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions)); _networkingOptions = networkingOptions ?? throw new ArgumentNullException(nameof(networkingOptions)); _sslOptions = sslOptions ?? throw new ArgumentNullException(nameof(sslOptions)); _correlationIdSequence = correlationIdSequence ?? throw new ArgumentNullException(nameof(correlationIdSequence)); _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); _logger = loggerFactory.CreateLogger <MemberConnection>(); HConsole.Configure(x => x.Configure <MemberConnection>().SetIndent(4).SetPrefix("MBR.CONN")); }
/// <summary> /// Initializes a new instance of the <see cref="MemberConnection"/> class. /// </summary> /// <param name="address">The network address.</param> /// <param name="messagingOptions">Messaging options.</param> /// <param name="socketOptions">Socket options.</param> /// <param name="sslOptions">SSL options.</param> /// <param name="connectionIdSequence">A sequence of unique connection identifiers.</param> /// <param name="correlationIdSequence">A sequence of unique correlation identifiers.</param> /// <param name="loggerFactory">A logger factory.</param> /// <remarks> /// <para>The <paramref name="connectionIdSequence"/> parameter can be used to supply a /// sequence of unique connection identifiers. This can be convenient for tests, where /// using unique identifiers across all clients can simplify debugging.</para> /// </remarks> public MemberConnection(NetworkAddress address, MessagingOptions messagingOptions, SocketOptions socketOptions, SslOptions sslOptions, ISequence <int> connectionIdSequence, ISequence <long> correlationIdSequence, ILoggerFactory loggerFactory) { Address = address ?? throw new ArgumentNullException(nameof(address)); _messagingOptions = messagingOptions ?? throw new ArgumentNullException(nameof(messagingOptions)); _socketOptions = socketOptions ?? throw new ArgumentNullException(nameof(socketOptions)); _sslOptions = sslOptions ?? throw new ArgumentNullException(nameof(sslOptions)); _connectionIdSequence = connectionIdSequence ?? throw new ArgumentNullException(nameof(connectionIdSequence)); _correlationIdSequence = correlationIdSequence ?? throw new ArgumentNullException(nameof(correlationIdSequence)); _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); _logger = loggerFactory.CreateLogger <MemberConnection>(); HConsole.Configure(this, config => config.SetIndent(4).SetPrefix("CLIENT")); }
//UNDONE: get configuration through IOptions and register SecuritySystem as a service. public SecuritySystem(ISecurityDataProvider dataProvider, IMessageProvider messageProvider, IMissingEntityHandler missingEntityHandler, SecurityConfiguration configuration, MessagingOptions messagingOptions) { Configuration = configuration; MessagingOptions = messagingOptions; dataProvider.ActivitySerializer = new ActivitySerializer(this); DataHandler = new DataHandler(dataProvider, Options.Create(messagingOptions)); ActivityHistory = new SecurityActivityHistoryController(); DataProvider = dataProvider; MessageProvider = messageProvider; MessageSenderManager = messageProvider.MessageSenderManager; MissingEntityHandler = missingEntityHandler; SystemUser = new SecuritySystemUser(configuration.SystemUserId); }
public static MessagingOptions UseServiceBusBroker( this MessagingOptions options, Action <IMessageBroker> brokerAction = null, string topicName = null, string subscriptionName = null, string section = "naos:messaging:serviceBus") { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); var configuration = options.Context.Configuration.GetSection(section).Get <ServiceBusConfiguration>(); configuration.EntityPath = topicName ?? $"{Environment.GetEnvironmentVariable(EnvironmentKeys.Environment) ?? "Production"}-Naos.Messaging"; options.Context.Services.AddSingleton <IServiceBusProvider>(sp => { if (configuration?.Enabled == true) { return(new ServiceBusProvider( sp.GetRequiredService <ILogger <ServiceBusProvider> >(), SdkContext.AzureCredentialsFactory.FromServicePrincipal(configuration.ClientId, configuration.ClientSecret, configuration.TenantId, AzureEnvironment.AzureGlobalCloud), configuration)); } throw new NotImplementedException("no messaging servicebus is enabled"); }); options.Context.Services.AddSingleton <IMessageBroker>(sp => { var broker = new ServiceBusMessageBroker(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Mediator((IMediator)sp.CreateScope().ServiceProvider.GetService(typeof(IMediator))) .Provider(sp.GetRequiredService <IServiceBusProvider>()) .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp)) .Map(sp.GetRequiredService <ISubscriptionMap>()) .SubscriptionName(subscriptionName ?? options.Context.Descriptor.Name) //AppDomain.CurrentDomain.FriendlyName, // PRODUCT.CAPABILITY .FilterScope(Environment.GetEnvironmentVariable(EnvironmentKeys.IsLocal).ToBool() ? Environment.MachineName.Humanize().Dehumanize().ToLower() : string.Empty)); brokerAction?.Invoke(broker); return(broker); }); // scope the messagebus messages to the local machine, so local events are handled locally options.Context.Services.AddHealthChecks() .AddAzureServiceBusTopic(configuration.ConnectionString, configuration.EntityPath, "messaging-broker-servicebus"); options.Context.Messages.Add($"{LogEventKeys.Startup} naos services builder: messaging added (broker={nameof(ServiceBusMessageBroker)})"); return(options); }
public MongoOutbox(IMongoDatabase database, IModuleRegistry moduleRegistry, OutboxOptions outboxOptions, MessagingOptions messagingOptions, IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher, ILogger <MongoOutbox> logger) { _database = database; _moduleClient = moduleClient; _asyncMessageDispatcher = asyncMessageDispatcher; _logger = logger; Enabled = outboxOptions.Enabled; _modules = moduleRegistry.Modules.ToArray(); _useBackgroundDispatcher = messagingOptions.UseBackgroundDispatcher; _collectionName = string.IsNullOrWhiteSpace(outboxOptions.CollectionName) ? "outbox" : outboxOptions.CollectionName; }
public void Options() { var options = new MessagingOptions { MinRetryDelayMilliseconds = 456, MaxFastInvocationCount = 789 }; Assert.That(options.MinRetryDelayMilliseconds, Is.EqualTo(456)); Assert.That(options.MaxFastInvocationCount, Is.EqualTo(789)); var clone = options.Clone(); Assert.That(clone.MinRetryDelayMilliseconds, Is.EqualTo(456)); Assert.That(clone.MaxFastInvocationCount, Is.EqualTo(789)); }
public SharedCallbackData( Func <Message, bool> resendFunc, Action <Message> unregister, ILogger logger, MessagingOptions messagingOptions, SerializationManager serializationManager, ApplicationRequestsStatisticsGroup requestStatistics) { RequestStatistics = requestStatistics; this.ShouldResend = resendFunc; this.Unregister = unregister; this.serializationManager = serializationManager; this.Logger = logger; this.MessagingOptions = messagingOptions; this.ResponseTimeout = messagingOptions.ResponseTimeout; }
public MessagesService(IOptions <MessagingOptions> messagingOptions, SendMessageService sendMessageService, IMapper mapper, ILogger <MessagesService> logger) { _messagingOptions = messagingOptions.Value; _sendMessageService = sendMessageService; _mapper = mapper; _logger = logger; _subscriptionClient = new SubscriptionClient( _messagingOptions.ServiceBusConnectionString, _messagingOptions.TopicNameToListen, _messagingOptions.SubscriptionName); }
public static MessagingOptions UseFileStorageBroker( this MessagingOptions options, Action <IMessageBroker> brokerAction = null, string messageScope = null, string section = "naos:messaging:fileStorage") { EnsureArg.IsNotNull(options, nameof(options)); EnsureArg.IsNotNull(options.Context, nameof(options.Context)); var configuration = options.Context.Configuration.GetSection(section).Get <FileStorageConfiguration>(); if (configuration?.Enabled == true) { options.Context.Services.AddScoped <IMessageBroker>(sp => { configuration.Folder = configuration.Folder.EmptyToNull() ?? Path.GetTempPath(); var broker = new FileStorageMessageBroker(o => o .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Tracer(sp.GetService <ITracer>()) .Mediator((IMediator)sp.CreateScope().ServiceProvider.GetService(typeof(IMediator))) .HandlerFactory(new ServiceProviderMessageHandlerFactory(sp)) .Storage(new FileStorageLoggingDecorator( sp.GetRequiredService <ILoggerFactory>(), new FolderFileStorage(s => s .LoggerFactory(sp.GetRequiredService <ILoggerFactory>()) .Folder(configuration.Folder) .Serializer(new JsonNetSerializer())))) .ProcessDelay(configuration.ProcessDelay) .Subscriptions(sp.GetRequiredService <ISubscriptionMap>()) .FilterScope(Environment.GetEnvironmentVariable(EnvironmentKeys.IsLocal).ToBool() ? Environment.MachineName.Humanize().Dehumanize().ToLower() : string.Empty) .MessageScope(messageScope)); brokerAction?.Invoke(broker); return(broker); }); options.Context.Messages.Add($"naos services builder: messaging added (broker={nameof(FileStorageMessageBroker)})"); } else { throw new NaosException("no messaging filestorage is enabled"); } return(options); }