private MessageHandlerEnumerator GetHandlerEnumerator(IMessage message, List <IMessageHandler> handlers)
        {
            if (LoadBalancingStrategy != null)
            {
                var index = LoadBalancingStrategy.GetNextHandlerStartIndex(message, handlers);
                return(new MessageHandlerEnumerator(index, handlers));
            }

            return(new MessageHandlerEnumerator(0, handlers));
        }
Exemple #2
0
        public RoutingSettings(Uri initServerUri, IDictionary <string, string> routingContext, Config config)
        {
            Throw.ArgumentNullException.IfNull(initServerUri, nameof(initServerUri));
            Throw.ArgumentNullException.IfNull(routingContext, nameof(routingContext));
            Throw.ArgumentNullException.IfNull(config, nameof(config));

            InitialServerAddressProvider = new InitialServerAddressProvider(initServerUri, config.Resolver);
            RoutingContext = routingContext;
            Strategy       = config.LoadBalancingStrategy;
        }
Exemple #3
0
 public RoutingSettings(Uri initServers, IDictionary <string, string> routingContext, Config config)
 {
     Throw.ArgumentNullException.IfNull(initServers, nameof(initServers));
     Throw.ArgumentNullException.IfNull(routingContext, nameof(routingContext));
     Throw.ArgumentNullException.IfNull(config, nameof(config));
     InitialServers = new HashSet <Uri> {
         initServers
     };
     RoutingContext = routingContext;
     Strategy       = config.LoadBalancingStrategy;
 }
        public async Task EventsCanBeReadByOneProcessorClient(LoadBalancingStrategy loadBalancingStrategy)
        {
            // Setup the environment.

            await using EventHubScope scope = await EventHubScope.CreateAsync(2);

            var connectionString = EventHubsTestEnvironment.Instance.BuildConnectionStringForEventHub(scope.EventHubName);

            using var cancellationSource = new CancellationTokenSource();
            cancellationSource.CancelAfter(EventHubsTestEnvironment.Instance.TestExecutionTimeLimit);

            // Send a set of events.

            var sourceEvents = EventGenerator.CreateEvents(50).ToList();
            var sentCount    = await SendEvents(connectionString, sourceEvents, cancellationSource.Token);

            Assert.That(sentCount, Is.EqualTo(sourceEvents.Count), "Not all of the source events were sent.");

            // Attempt to read back the events.

            var processedEvents  = new ConcurrentDictionary <string, EventData>();
            var completionSource = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
            var options          = new EventProcessorOptions {
                LoadBalancingUpdateInterval = TimeSpan.FromMilliseconds(250), LoadBalancingStrategy = loadBalancingStrategy
            };
            var processor = CreateProcessor(scope.ConsumerGroups.First(), connectionString, options: options);

            processor.ProcessErrorAsync += CreateAssertingErrorHandler();
            processor.ProcessEventAsync += CreateEventTrackingHandler(sentCount, processedEvents, completionSource, cancellationSource.Token);

            await processor.StartProcessingAsync(cancellationSource.Token);

            await Task.WhenAny(completionSource.Task, Task.Delay(Timeout.Infinite, cancellationSource.Token));

            Assert.That(cancellationSource.IsCancellationRequested, Is.False, "The cancellation token should not have been signaled.");

            await processor.StopProcessingAsync(cancellationSource.Token);

            cancellationSource.Cancel();

            // Validate the events that were processed.

            foreach (var sourceEvent in sourceEvents)
            {
                var sourceId = sourceEvent.Properties[EventGenerator.IdPropertyName].ToString();
                Assert.That(processedEvents.TryGetValue(sourceId, out var processedEvent), Is.True, $"The event with custom identifier [{ sourceId }] was not processed.");
                Assert.That(sourceEvent.IsEquivalentTo(processedEvent), $"The event with custom identifier [{ sourceId }] did not match the corresponding processed event.");
            }
        }
Exemple #5
0
 private static ILoadBalancingStrategy CreateLoadBalancingStrategy(LoadBalancingStrategy strategy, IClusterConnectionPool pool,
                                                                   ILogger logger)
 {
     if (strategy == LoadBalancingStrategy.LeastConnected)
     {
         return(new LeastConnectedLoadBalancingStrategy(pool, logger));
     }
     else if (strategy == LoadBalancingStrategy.RoundRobin)
     {
         return(new RoundRobinLoadBalancingStrategy(logger));
     }
     else
     {
         throw new ArgumentException($"Unknown load balancing strategy: {strategy}");
     }
 }
        /// <summary>
        ///     Initializes a new instance of the <see cref="LavalinkCluster"/> class.
        /// </summary>
        /// <param name="options">the cluster options</param>
        /// <param name="client">the discord client</param>
        /// <param name="logger">the logger</param>
        /// <param name="cache">
        ///     a cache that is shared between the different lavalink rest clients. If the cache is
        ///     <see langword="null"/>, no cache will be used.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     thrown if the specified <paramref name="options"/> parameter is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     thrown if the specified <paramref name="client"/> is <see langword="null"/>.
        /// </exception>
        public LavalinkCluster(LavalinkClusterOptions options, IDiscordClientWrapper client, ILogger logger = null, ILavalinkCache cache = null)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _client = client ?? throw new ArgumentNullException(nameof(client));

            _loadBalacingStrategy = options.LoadBalacingStrategy;
            _logger    = logger;
            _cache     = cache;
            _nodesLock = new object();
            StayOnline = options.StayOnline;
            _nodes     = options.Nodes.Select(CreateNode).ToList();
        }