<commit_before>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Runtime.Messaging;

namespace Orleans.Messaging
{
    /// <summary>
    /// The GatewayManager class holds the list of known gateways, as well as maintaining the list of "dead" gateways.
    ///
    /// The known list can come from one of two places: the full list may appear in the client configuration object, or
    /// the config object may contain an IGatewayListProvider delegate. If both appear, then the delegate takes priority.
    /// </summary>
    internal class GatewayManager : IDisposable
    {
        private readonly object lockable = new object();
        private readonly Dictionary<SiloAddress, DateTime> knownDead = new Dictionary<SiloAddress, DateTime>();
        private readonly Dictionary<SiloAddress, DateTime> knownMasked = new Dictionary<SiloAddress, DateTime>();
        private readonly IGatewayListProvider gatewayListProvider;
        private readonly ILogger logger;
        private readonly ConnectionManager connectionManager;
        private readonly GatewayOptions gatewayOptions;
        private AsyncTaskSafeTimer gatewayRefreshTimer;
        private List<SiloAddress> cachedLiveGateways;
        private HashSet<SiloAddress> cachedLiveGatewaysSet;
        private List<SiloAddress> knownGateways;
        private DateTime lastRefreshTime;
        private int roundRobinCounter;
        private bool gatewayRefreshCallInitiated;
        private bool gatewayListProviderInitialized;

        public GatewayManager(
            IOptions<GatewayOptions> gatewayOptions,
            IGatewayListProvider gatewayListProvider,
            ILoggerFactory loggerFactory,
            ConnectionManager connectionManager)
        {
            this.gatewayOptions = gatewayOptions.Value;
            this.logger = loggerFactory.CreateLogger<GatewayManager>();
            this.connectionManager = connectionManager;
            this.gatewayListProvider = gatewayListProvider;
            this.gatewayRefreshTimer = new AsyncTaskSafeTimer(
                loggerFactory.CreateLogger<SafeTimer>(),
                RefreshSnapshotLiveGateways_TimerCallback,
                null,
                this.gatewayOptions.GatewayListRefreshPeriod,
                this.gatewayOptions.GatewayListRefreshPeriod);
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (!gatewayListProviderInitialized)
            {
                await this.gatewayListProvider.InitializeGatewayListProvider();
                gatewayListProviderInitialized = true;
            }

            var knownGateways = await this.gatewayListProvider.GetGateways();
            if (knownGateways.Count == 0)
            {
                var err = $"Could not find any gateway in {this.gatewayListProvider.GetType().FullName}. Orleans client cannot initialize.";
                this.logger.LogError((int)ErrorCode.GatewayManager_NoGateways, err);
                throw new SiloUnavailableException(err);
            }

            this.logger.LogInformation(
                (int)ErrorCode.GatewayManager_FoundKnownGateways,
                "Found {GatewayCount} gateways: {Gateways}",
                knownGateways.Count,
                Utils.EnumerableToString(knownGateways));

            this.roundRobinCounter = this.gatewayOptions.PreferedGatewayIndex >= 0 ? this.gatewayOptions.PreferedGatewayIndex : ThreadSafeRandom.Next(knownGateways.Count);
            this.knownGateways = this.cachedLiveGateways = knownGateways.Select(gw => gw.ToGatewayAddress()).ToList();<commit_msg>Fix potential NullReferenceException during GatewayManager initialization (#7540)<commit_after>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Runtime.Messaging;

namespace Orleans.Messaging
{
    /// <summary>
    /// The GatewayManager class holds the list of known gateways, as well as maintaining the list of "dead" gateways.
    ///
    /// The known list can come from one of two places: the full list may appear in the client configuration object, or
    /// the config object may contain an IGatewayListProvider delegate. If both appear, then the delegate takes priority.
    /// </summary>
    internal class GatewayManager : IDisposable
    {
        private readonly object lockable = new object();
        private readonly Dictionary<SiloAddress, DateTime> knownDead = new Dictionary<SiloAddress, DateTime>();
        private readonly Dictionary<SiloAddress, DateTime> knownMasked = new Dictionary<SiloAddress, DateTime>();
        private readonly IGatewayListProvider gatewayListProvider;
        private readonly ILogger logger;
        private readonly ConnectionManager connectionManager;
        private readonly GatewayOptions gatewayOptions;
        private AsyncTaskSafeTimer gatewayRefreshTimer;
        private List<SiloAddress> cachedLiveGateways;
        private HashSet<SiloAddress> cachedLiveGatewaysSet;
        private List<SiloAddress> knownGateways;
        private DateTime lastRefreshTime;
        private int roundRobinCounter;
        private bool gatewayRefreshCallInitiated;
        private bool gatewayListProviderInitialized;

        private readonly ILogger<SafeTimer> timerLogger;

        public GatewayManager(
            IOptions<GatewayOptions> gatewayOptions,
            IGatewayListProvider gatewayListProvider,
            ILoggerFactory loggerFactory,
            ConnectionManager connectionManager)
        {
            this.gatewayOptions = gatewayOptions.Value;
            this.logger = loggerFactory.CreateLogger<GatewayManager>();
            this.connectionManager = connectionManager;
            this.gatewayListProvider = gatewayListProvider;
            this.timerLogger = loggerFactory.CreateLogger<SafeTimer>();
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (!gatewayListProviderInitialized)
            {
                await this.gatewayListProvider.InitializeGatewayListProvider();
                gatewayListProviderInitialized = true;
            }

            this.gatewayRefreshTimer = new AsyncTaskSafeTimer(
                this.timerLogger,
                RefreshSnapshotLiveGateways_TimerCallback,
                null,
                this.gatewayOptions.GatewayListRefreshPeriod,
                this.gatewayOptions.GatewayListRefreshPeriod);

            var knownGateways = await this.gatewayListProvider.GetGateways();
            if (knownGateways.Count == 0)
            {
                var err = $"Could not find any gateway in {this.gatewayListProvider.GetType().FullName}. Orleans client cannot initialize.";
                this.logger.LogError((int)ErrorCode.GatewayManager_NoGateways, err);
                throw new SiloUnavailableException(err);
            }

            this.logger.LogInformation(
                (int)ErrorCode.GatewayManager_FoundKnownGateways,
                "Found {GatewayCount} gateways: {Gateways}",
                knownGateways.Count,
                Utils.EnumerableToString(knownGateways));

            this.roundRobinCounter = this.gatewayOptions.PreferedGatewayIndex >= 0 ? this.gatewayOptions.PreferedGatewayIndex : ThreadSafeRandom.Next(knownGateways.Count);
            this.knownGateways = this.cachedLiveGateways = knownGateways.Select(gw => gw.ToGatewayAddress()).ToList();
{'fraction_non_alphanumeric': 0.06747843734145104, 'fraction_numerical': 0.0010147133434804667, 'mean_word_length': 2.8957509881422925, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '967980', 'n_tokens_mistral': 1843, 'n_tokens_neox': 1806, 'n_words': 469}