Exemplo n.º 1
0
        public Server(IOStrategy ioStrategy, IViewClient viewClient, IQueryClient queryClient, INodeAdapter nodeAdapter,
                      ClientConfiguration clientConfiguration, ITypeTranscoder transcoder, IBucketConfig bucketConfig)
        {
            _ioStrategy = ioStrategy;
            _ioStrategy.ConnectionPool.Owner = this;
            _nodeAdapter         = nodeAdapter;
            _clientConfiguration = clientConfiguration;
            _timingEnabled       = _clientConfiguration.EnableOperationTiming;
            _typeTranscoder      = transcoder;
            _bucketConfig        = bucketConfig;

            //services that this node is responsible for
            IsMgmtNode  = _nodeAdapter.MgmtApi > 0;
            IsDataNode  = _nodeAdapter.KeyValue > 0;
            IsQueryNode = _nodeAdapter.N1QL > 0;
            IsIndexNode = _nodeAdapter.IndexAdmin > 0;
            IsViewNode  = _nodeAdapter.Views > 0;

            //View and query clients
            ViewClient  = viewClient;
            QueryClient = queryClient;

            //timer and node status
            _heartBeatTimer = new Timer(1000)
            {
                Enabled = false
            };
            _heartBeatTimer.Elapsed += _heartBeatTimer_Elapsed;
            TakeOffline(_ioStrategy.ConnectionPool.InitializationFailed);
        }
Exemplo n.º 2
0
        void INotificationHandler.HandleResponse(IQueryClient queryClient, string responseText)
        {
            CommandParameterGroupList parameterGroupList = CommandParameterGroupList.Parse(responseText);

            int?reasonId = parameterGroupList.GetParameterValue <int?>("reasonid") ?? (int)ClientLeftReason.Disconnect;

            switch ((ClientLeftReason)reasonId.Value)
            {
            case ClientLeftReason.Kicked:
                Kicked?.Invoke(queryClient, new ClientKickEventArgs(parameterGroupList));
                break;

            case ClientLeftReason.Banned:
                Banned?.Invoke(queryClient, new ClientBanEventArgs(parameterGroupList));
                break;

            case ClientLeftReason.ConnectionLost:
                ConnectionLost?.Invoke(queryClient, new ClientConnectionLostEventArgs(parameterGroupList));
                break;

            case ClientLeftReason.Disconnect:
                Disconnected?.Invoke(queryClient, new ClientDisconnectEventArgs(parameterGroupList));
                break;
            }
        }
Exemplo n.º 3
0
 public JobImpactManager(
     IConfigSection configSection,
     IQueryClient queryClient)
 {
     this.configSection = configSection.Validate("configSection");
     this.QueryClient   = queryClient.Validate("queryClient");
 }
Exemplo n.º 4
0
        private static void Connect(IQueryClient client)
        {
            QueryClient.ConnectResponse connectResponse = client.Connect();

            Console.WriteLine($"Connected: {connectResponse.Success}");
            Console.WriteLine($"Query-Target: {connectResponse.QueryType}");
            Console.WriteLine($"Greeting: {connectResponse.Greeting}");
        }
Exemplo n.º 5
0
 public FakeServer(IConnectionPool connectionPool, IViewClient viewClient, IQueryClient queryClient, IPEndPoint endPoint, IOStrategy strategy)
 {
     ConnectionPool = connectionPool;
     ViewClient     = viewClient;
     QueryClient    = queryClient;
     EndPoint       = endPoint;
     Strategy       = strategy;
 }
Exemplo n.º 6
0
 public FakeServer(IConnectionPool connectionPool, IViewClient viewClient, IQueryClient queryClient, IPEndPoint endPoint, IIOService service)
 {
     ConnectionPool = connectionPool;
     ViewClient     = viewClient;
     QueryClient    = queryClient;
     EndPoint       = endPoint;
     Service        = service;
 }
Exemplo n.º 7
0
        public static Task <IQueryResult <T> > QueryAsync <T>(this IQueryClient client, string statement, Action <QueryOptions> configureOptions)
        {
            var options = new QueryOptions();

            configureOptions(options);

            return(client.QueryAsync <T>(statement, options));
        }
Exemplo n.º 8
0
 public Server(IOStrategy ioStrategy, IViewClient viewClient, IQueryClient queryClient, Node nodeInfo, ClientConfiguration clientConfiguration)
 {
     _ioStrategy          = ioStrategy;
     ViewClient           = viewClient;
     QueryClient          = queryClient;
     _nodeInfo            = nodeInfo;
     _clientConfiguration = clientConfiguration;
 }
Exemplo n.º 9
0
        protected void HandleRawNotificationOnSyncContextOrInCurrentThread(IQueryClient queryClient, string notificationName, string responseText)
        {
            INotificationHandler handler;

            if (NotificationHandlerMapping.TryGetValue(notificationName, out handler) || NotificationHandlerMapping.TryGetValue("*", out handler))
            {
                handler.HandleResponse(queryClient, responseText);
            }
        }
Exemplo n.º 10
0
 public Server(IOStrategy ioStrategy, IViewClient viewClient, IQueryClient queryClient, Node nodeInfo, ClientConfiguration clientConfiguration)
 {
     _ioStrategy          = ioStrategy;
     ViewClient           = viewClient;
     QueryClient          = queryClient;
     _nodeInfo            = nodeInfo;
     _clientConfiguration = clientConfiguration;
     _timingEnabled       = _clientConfiguration.EnableOperationTiming;
 }
Exemplo n.º 11
0
        public Server(IIOService ioService, IViewClient viewClient, IViewClient streamingViewClient, IQueryClient queryClient, IQueryClient streamingQueryClient, ISearchClient searchClient,
                      IAnalyticsClient analyticsClient, INodeAdapter nodeAdapter,
                      ClientConfiguration clientConfiguration, ITypeTranscoder transcoder, IBucketConfig bucketConfig)
        {
            if (ioService != null)
            {
                _ioService = ioService;
                _ioService.ConnectionPool.Owner = this;
            }
            _nodeAdapter         = nodeAdapter;
            _clientConfiguration = clientConfiguration;
            _bucketConfiguration = clientConfiguration.BucketConfigs[bucketConfig.Name];
            _timingEnabled       = _clientConfiguration.EnableOperationTiming;
            _typeTranscoder      = transcoder;
            _bucketConfig        = bucketConfig;

            //services that this node is responsible for
            IsMgmtNode      = _nodeAdapter.MgmtApi > 0;
            IsDataNode      = _nodeAdapter.KeyValue > 0;
            IsQueryNode     = _nodeAdapter.N1QL > 0;
            IsIndexNode     = _nodeAdapter.IndexAdmin > 0;
            IsViewNode      = _nodeAdapter.Views > 0;
            IsSearchNode    = _nodeAdapter.IsSearchNode;
            IsAnalyticsNode = _nodeAdapter.IsAnalyticsNode;

            //View and query clients
            ViewClient            = viewClient;
            _streamingViewClient  = streamingViewClient;
            QueryClient           = queryClient;
            SearchClient          = searchClient;
            _streamingQueryClient = streamingQueryClient;
            AnalyticsClient       = analyticsClient;

            CachedViewBaseUri  = UrlUtil.GetViewBaseUri(_nodeAdapter, _bucketConfiguration);
            CachedQueryBaseUri = UrlUtil.GetN1QLBaseUri(_nodeAdapter, _bucketConfiguration);

            if (IsDataNode || IsQueryNode)
            {
                _lastIOErrorCheckedTime = DateTime.Now;

                //On initialization, data nodes are authenticated, so they can start in a down state.
                //If the node is down immediately start the timer, otherwise disable it.
                if (IsDataNode)
                {
                    _isDown = _ioService.ConnectionPool.InitializationFailed;
                }

                Log.Info("Initialization {0} for node {1}", _isDown ? "failed" : "succeeded", EndPoint);

                //timer and node status
                _heartBeatTimer = new Timer(_heartBeatTimer_Elapsed, null, Timeout.Infinite, Timeout.Infinite);
                if (_isDown)
                {
                    StartHeartbeatTimer();
                }
            }
        }
Exemplo n.º 12
0
 public AnalyticsIndexManager(ILogger <AnalyticsIndexManager> logger, IQueryClient client, IRedactor redactor,
                              IServiceUriProvider serviceUriProvider, CouchbaseHttpClient couchbaseHttpClient)
 {
     _logger              = logger ?? throw new ArgumentNullException(nameof(logger));
     _client              = client ?? throw new ArgumentNullException(nameof(client));
     _redactor            = redactor ?? throw new ArgumentNullException(nameof(redactor));
     _serviceUriProvider  = serviceUriProvider ?? throw new ArgumentNullException(nameof(serviceUriProvider));
     _couchbaseHttpClient = couchbaseHttpClient ?? throw new ArgumentNullException(nameof(couchbaseHttpClient));
 }
        /// <remarks>
        /// If <see cref="configSettings"/> is null, a default value is used.
        /// </remarks>
        public MockInfrastructureCoordinatorFactory(IManagementClient managementClient, IDictionary <string, string> configSettings = null, IQueryClient queryClient = null, IInfrastructureAgentWrapper agent = null)
        {
            managementClient.ThrowIfNull("managementClient");

            this.managementClient = managementClient;
            this.configSettings   = configSettings != null
                ? new Dictionary <string, string>(configSettings, StringComparer.OrdinalIgnoreCase)
                : new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            this.queryClient = queryClient ?? new MockQueryClient();
            this.agent       = agent ?? new MockInfrastructureAgentWrapper();
        }
Exemplo n.º 14
0
        public Task <IQueryResult <T> > Query <T>(string statement, QueryParameter parameters = null, IQueryOptions options = null)
        {
            if (_queryClient == null)
            {
                _queryClient = new QueryClient(_configuration);
            }

            //re-use older API by mapping parameters to new API
            options?.AddNamedParameter(parameters?.NamedParameters.ToArray());
            options?.AddPositionalParameter(parameters?.PostionalParameters.ToArray());

            return(_queryClient.QueryAsync <T>(statement, options));
        }
Exemplo n.º 15
0
        public Server(IOStrategy ioStrategy, IViewClient viewClient, IQueryClient queryClient, INodeAdapter nodeAdapter,
                      ClientConfiguration clientConfiguration, ITypeTranscoder transcoder, IBucketConfig bucketConfig)
        {
            if (ioStrategy != null)
            {
                _ioStrategy = ioStrategy;
                _ioStrategy.ConnectionPool.Owner = this;
            }
            _nodeAdapter         = nodeAdapter;
            _clientConfiguration = clientConfiguration;
            _bucketConfiguration = clientConfiguration.BucketConfigs[bucketConfig.Name];
            _timingEnabled       = _clientConfiguration.EnableOperationTiming;
            _typeTranscoder      = transcoder;
            _bucketConfig        = bucketConfig;

            //services that this node is responsible for
            IsMgmtNode  = _nodeAdapter.MgmtApi > 0;
            IsDataNode  = _nodeAdapter.KeyValue > 0;
            IsQueryNode = _nodeAdapter.N1QL > 0;
            IsIndexNode = _nodeAdapter.IndexAdmin > 0;
            IsViewNode  = _nodeAdapter.Views > 0;

            //View and query clients
            ViewClient  = viewClient;
            QueryClient = queryClient;

            CachedViewBaseUri  = UrlUtil.GetViewBaseUri(_nodeAdapter, _bucketConfiguration);
            CachedQueryBaseUri = UrlUtil.GetN1QLBaseUri(_nodeAdapter, _bucketConfiguration);

            if (IsDataNode || IsQueryNode)
            {
                _lastIOErrorCheckedTime = DateTime.Now;

                //On initialization, data nodes are authenticated, so they can start in a down state.
                //If the node is down immediately start the timer, otherwise disable it.
                if (IsDataNode)
                {
                    _isDown = _ioStrategy.ConnectionPool.InitializationFailed;
                }

                Log.InfoFormat("Initialization {0} for node {1}", _isDown ? "failed" : "succeeded", EndPoint);

                //timer and node status
                _heartBeatTimer = new Timer(_clientConfiguration.NodeAvailableCheckInterval)
                {
                    Enabled = _isDown
                };
                _heartBeatTimer.Elapsed += _heartBeatTimer_Elapsed;
            }
        }
Exemplo n.º 16
0
        public Server(IIOService ioService, IViewClient viewClient, IViewClient streamingViewClient, IQueryClient queryClient, IQueryClient streamingQueryClient, ISearchClient searchClient,
                      IAnalyticsClient analyticsClient, INodeAdapter nodeAdapter, ITypeTranscoder transcoder, ConfigContextBase context)
        {
            if (ioService != null)
            {
                _ioService = ioService;
                _ioService.ConnectionPool.Owner = this;
            }

            _clientConfiguration = context.ClientConfig;
            _bucketConfiguration = context.ClientConfig.BucketConfigs[context.BucketConfig.Name];
            _timingEnabled       = _clientConfiguration.EnableOperationTiming;
            _typeTranscoder      = transcoder;
            _bucketConfig        = context.BucketConfig;

            //set all properties based off the nodes and nodeExt adapter
            LoadNodeAdapter(nodeAdapter);

            //View and query clients
            ViewClient            = viewClient;
            _streamingViewClient  = streamingViewClient;
            QueryClient           = queryClient;
            SearchClient          = searchClient;
            _streamingQueryClient = streamingQueryClient;
            AnalyticsClient       = analyticsClient;

            if (IsDataNode || IsQueryNode)
            {
                _lastIOErrorCheckedTime = DateTime.Now;

                //On initialization, data nodes are authenticated, so they can start in a down state.
                //If the node is down immediately start the timer, otherwise disable it.
                if (IsDataNode)
                {
                    _isDown = _ioService.ConnectionPool.InitializationFailed;
                }

                Log.Info("Initialization {0} for node {1}", _isDown ? "failed" : "succeeded", EndPoint);

                //timer and node status
                _heartBeatTimer = new Timer(_heartBeatTimer_Elapsed, null, Timeout.Infinite, Timeout.Infinite);
                if (_isDown)
                {
                    StartHeartbeatTimer();
                }
            }
        }
Exemplo n.º 17
0
 public static void AddQueryClient <TInterface>(IQueryClient queryClient) where TInterface : IBaseProvider
 {
     lock (serviceLock)
     {
         Type interfaceType = typeof(TInterface);
         if (queryServerTypes.Contains(interfaceType))
         {
             throw new InvalidOperationException($"Cannot create loopback. Query Server already registered for type {interfaceType.GetNiceName()}");
         }
         if (commandClients.Keys.Contains(interfaceType))
         {
             throw new InvalidOperationException($"Query Client already registered for type {interfaceType.GetNiceName()}");
         }
         queryClients.TryAdd(interfaceType, queryClient);
         _ = Log.InfoAsync($"{nameof(Bus)} Added Query Client For {interfaceType.GetNiceName()}");
     }
 }
Exemplo n.º 18
0
        private void HandleRawNotificationAsync(IQueryClient queryClient, string notificationName, string responseText)
        {
            SendOrPostCallback callback = state =>
            {
                object[] values = (object[])state;
                HandleRawNotificationOnSyncContextOrInCurrentThread((IQueryClient)values[0], (string)values[1], (string)values[2]);
            };

            object[] callBackState = { queryClient, notificationName, responseText };

            if (SynchronizationContext == null)
            {
                callback(callBackState);
            }
            else
            {
                SynchronizationContext.Post(callback, callBackState);
            }
        }
        void INotificationHandler.HandleResponse(IQueryClient queryClient, string responseText)
        {
            CommandParameterGroupList parameterGroupList = CommandParameterGroupList.Parse(responseText);

            MessageTarget messageTarget = (MessageTarget)parameterGroupList.GetParameterValue <uint>("targetmode");

            switch (messageTarget)
            {
            case MessageTarget.Client:
                ReceivedFromClient?.Invoke(queryClient, new MessageReceivedEventArgs(parameterGroupList));
                break;

            case MessageTarget.Channel:
                ReceivedFromChannel?.Invoke(queryClient, new MessageReceivedEventArgs(parameterGroupList));
                break;

            case MessageTarget.Server:
                ReceivedFromServer?.Invoke(queryClient, new MessageReceivedEventArgs(parameterGroupList));
                break;
            }
        }
Exemplo n.º 20
0
        void INotificationHandler.HandleResponse(IQueryClient queryClient, string responseText)
        {
            CommandParameterGroupList parameterGroupList = CommandParameterGroupList.Parse(responseText);

            int?invokerId = parameterGroupList.GetParameterValue <int?>("invokerid");

            if (!invokerId.HasValue)
            {
                JoiningChannel?.Invoke(queryClient, new ClientMovedEventArgs(parameterGroupList));
                return;
            }

            if (invokerId == 0)
            {
                CreatingTemporaryChannel?.Invoke(queryClient, new ClientMovedEventArgs(parameterGroupList));
            }
            else
            {
                JoiningChannelForced?.Invoke(queryClient, new ClientMovedByClientEventArgs(parameterGroupList));
            }
        }
 public IqSearchClient(Uri endpoint, IAuthentication auth, string indexName = "udp-index")
 {
     // get our query client defaulting to the rest query client
     _client = new RestQueryClient <T, R>(endpoint, auth, indexName);
 }
Exemplo n.º 22
0
        public static void StartServices(string serviceName, ServiceSettings serviceSettings, IServiceCreator serviceCreator, IRelayRegister relayRegister = null)
        {
            _ = Log.InfoAsync($"Starting {serviceName}");
            lock (serviceLock)
            {
                var serverSetting = serviceSettings.Services.FirstOrDefault(x => x.Name == serviceName);
                if (serverSetting == null)
                {
                    throw new Exception($"Service {serviceName} not found in {CQRSSettings.SettingsFileName}");
                }

                var serverUrl = Config.GetSetting("urls");
                if (String.IsNullOrWhiteSpace(serverUrl))
                {
                    serverUrl = Config.GetSetting("ASPNETCORE_URLS");
                }
                if (String.IsNullOrWhiteSpace(serverUrl))
                {
                    serverUrl = Config.GetSetting("DOTNET_URLS");
                }
                if (String.IsNullOrWhiteSpace(serverUrl))
                {
                    serverUrl = serverSetting.ExternalUrl;
                }

                ICommandServer commandServer = null;
                IEventServer   eventServer   = null;
                IQueryServer   queryServer   = null;

                var serverTypes = new HashSet <Type>();
                foreach (var clientSetting in serviceSettings.Services)
                {
                    if (clientSetting.Types == null || clientSetting.Types.Length == 0)
                    {
                        continue;
                    }
                    if (clientSetting != serverSetting)
                    {
                        continue;
                    }
                    foreach (var typeName in clientSetting.Types)
                    {
                        var type = Discovery.GetTypeFromName(typeName);
                        if (!type.IsInterface)
                        {
                            throw new Exception($"{type.GetNiceName()} is not an interface");
                        }
                        var typeDetails = TypeAnalyzer.GetTypeDetail(type);
                        if (!typeDetails.Interfaces.Contains(typeof(IBaseProvider)))
                        {
                            throw new Exception($"{type.GetNiceName()} does not inherit {nameof(IBaseProvider)}");
                        }

                        var commandTypes = GetCommandTypesFromInterface(type);
                        foreach (var commandType in commandTypes)
                        {
                            serverTypes.Add(commandType);
                        }

                        var eventTypes = GetEventTypesFromInterface(type);
                        foreach (var eventType in eventTypes)
                        {
                            serverTypes.Add(eventType);
                        }

                        if (typeDetails.Attributes.Any(x => x is ServiceExposedAttribute))
                        {
                            serverTypes.Add(type);
                        }
                    }
                }

                foreach (var serviceSetting in serviceSettings.Services)
                {
                    if (serviceSetting.Types == null || serviceSetting.Types.Length == 0)
                    {
                        continue;
                    }

                    ICommandClient commandClient = null;
                    IEventClient   eventClient   = null;
                    IQueryClient   queryClient   = null;

                    foreach (var typeName in serviceSetting.Types)
                    {
                        var type = Discovery.GetTypeFromName(typeName);
                        if (!type.IsInterface)
                        {
                            throw new Exception($"{type.GetNiceName()} is not an interface");
                        }
                        var typeDetails = TypeAnalyzer.GetTypeDetail(type);
                        if (!typeDetails.Interfaces.Contains(typeof(IBaseProvider)))
                        {
                            throw new Exception($"{type.GetNiceName()} does not inherit {nameof(IBaseProvider)}");
                        }

                        var commandTypes = GetCommandTypesFromInterface(type);
                        if (commandTypes.Count > 0)
                        {
                            if (serviceSetting == serverSetting)
                            {
                                if (commandServer == null)
                                {
                                    var encryptionKey = String.IsNullOrWhiteSpace(serviceSetting.EncryptionKey) ? null : SymmetricEncryptor.GetKey(serviceSetting.EncryptionKey);
                                    commandServer = serviceCreator.CreateCommandServer(serverUrl, encryptionKey);
                                    commandServer.SetHandler(HandleRemoteCommandDispatchAsync, HandleRemoteCommandDispatchAwaitAsync);
                                    if (!commandServers.Contains(commandServer))
                                    {
                                        commandServers.Add(commandServer);
                                    }
                                }
                                foreach (var commandType in commandTypes)
                                {
                                    if (commandClients.Keys.Contains(commandType))
                                    {
                                        throw new InvalidOperationException($"Command Client already registered for type {commandType.GetNiceName()}");
                                    }
                                    if (commandServerTypes.Contains(commandType))
                                    {
                                        throw new InvalidOperationException($"Command Server already registered for type {commandType.GetNiceName()}");
                                    }
                                    commandServerTypes.Add(commandType);
                                    commandServer.RegisterCommandType(commandType);
                                }
                            }
                            else
                            {
                                if (commandClient == null)
                                {
                                    var encryptionKey = String.IsNullOrWhiteSpace(serviceSetting.EncryptionKey) ? null : SymmetricEncryptor.GetKey(serviceSetting.EncryptionKey);
                                    commandClient = serviceCreator.CreateCommandClient(relayRegister?.RelayUrl ?? serviceSetting.ExternalUrl, encryptionKey);
                                }
                                var clientCommandTypes = commandTypes.Where(x => !serverTypes.Contains(x)).ToArray();
                                if (clientCommandTypes.Length > 0)
                                {
                                    foreach (var commandType in clientCommandTypes)
                                    {
                                        if (commandServerTypes.Contains(commandType))
                                        {
                                            throw new InvalidOperationException($"Command Server already registered for type {commandType.GetNiceName()}");
                                        }
                                        if (commandClients.Keys.Contains(commandType))
                                        {
                                            throw new InvalidOperationException($"Command Client already registered for type {commandType.GetNiceName()}");
                                        }
                                        commandClients.TryAdd(commandType, commandClient);
                                    }
                                }
                                else
                                {
                                    if (commandClient is IDisposable disposable)
                                    {
                                        disposable.Dispose();
                                    }
                                }
                            }
                        }

                        var eventTypes = GetEventTypesFromInterface(type);
                        if (eventTypes.Count > 0)
                        {
                            if (serviceSetting == serverSetting)
                            {
                                if (eventServer == null)
                                {
                                    var encryptionKey = String.IsNullOrWhiteSpace(serviceSetting.EncryptionKey) ? null : SymmetricEncryptor.GetKey(serviceSetting.EncryptionKey);
                                    eventServer = serviceCreator.CreateEventServer(serverUrl, encryptionKey);
                                    eventServer.SetHandler(HandleRemoteEventDispatchAsync);
                                    if (!eventServers.Contains(eventServer))
                                    {
                                        eventServers.Add(eventServer);
                                    }
                                }
                                foreach (var eventType in eventTypes)
                                {
                                    if (eventClients.Keys.Contains(eventType))
                                    {
                                        throw new InvalidOperationException($"Event Client already registered for type {eventType.GetNiceName()}");
                                    }
                                    if (eventServerTypes.Contains(eventType))
                                    {
                                        throw new InvalidOperationException($"Event Server already registered for type {eventType.GetNiceName()}");
                                    }
                                    eventServerTypes.Add(eventType);
                                    eventServer.RegisterEventType(eventType);
                                }
                            }
                            else
                            {
                                if (eventClient == null)
                                {
                                    var encryptionKey = String.IsNullOrWhiteSpace(serviceSetting.EncryptionKey) ? null : SymmetricEncryptor.GetKey(serviceSetting.EncryptionKey);
                                    eventClient = serviceCreator.CreateEventClient(relayRegister?.RelayUrl ?? serviceSetting.ExternalUrl, encryptionKey);
                                }
                                var clientEventTypes = eventTypes.Where(x => !serverTypes.Contains(x)).ToArray();
                                if (clientEventTypes.Length > 0)
                                {
                                    foreach (var eventType in eventTypes)
                                    {
                                        if (eventServerTypes.Contains(eventType))
                                        {
                                            throw new InvalidOperationException($"Event Server already registered for type {eventType.GetNiceName()}");
                                        }
                                        if (!eventClients.Keys.Contains(eventType))
                                        {
                                            eventClients.TryAdd(eventType, eventClient);
                                        }
                                    }
                                }
                                else
                                {
                                    if (eventClient is IDisposable disposable)
                                    {
                                        disposable.Dispose();
                                    }
                                }
                            }
                        }

                        if (typeDetails.Attributes.Any(x => x is ServiceExposedAttribute))
                        {
                            if (serviceSetting == serverSetting)
                            {
                                if (queryServer == null)
                                {
                                    var encryptionKey = String.IsNullOrWhiteSpace(serviceSetting.EncryptionKey) ? null : SymmetricEncryptor.GetKey(serviceSetting.EncryptionKey);
                                    queryServer = serviceCreator.CreateQueryServer(serverUrl, encryptionKey);
                                    queryServer.SetHandler(HandleRemoteQueryCallAsync);
                                    if (!queryServers.Contains(queryServer))
                                    {
                                        queryServers.Add(queryServer);
                                    }
                                }
                                if (queryClients.Keys.Contains(type))
                                {
                                    throw new InvalidOperationException($"Query Client already registered for type {type.GetNiceName()}");
                                }
                                if (queryServerTypes.Contains(type))
                                {
                                    throw new InvalidOperationException($"Query Server already registered for type {type.GetNiceName()}");
                                }
                                queryServerTypes.Add(type);
                                queryServer.RegisterInterfaceType(type);
                            }
                            else
                            {
                                if (queryClient == null)
                                {
                                    var encryptionKey = String.IsNullOrWhiteSpace(serviceSetting.EncryptionKey) ? null : SymmetricEncryptor.GetKey(serviceSetting.EncryptionKey);
                                    queryClient = serviceCreator.CreateQueryClient(relayRegister?.RelayUrl ?? serviceSetting.ExternalUrl, encryptionKey);
                                }
                                if (!serverTypes.Contains(type))
                                {
                                    if (queryServerTypes.Contains(type))
                                    {
                                        throw new InvalidOperationException($"Query Server already registered for type {type.GetNiceName()}");
                                    }
                                    if (commandClients.Keys.Contains(type))
                                    {
                                        throw new InvalidOperationException($"Query Client already registered for type {type.GetNiceName()}");
                                    }
                                    queryClients.TryAdd(type, queryClient);
                                }
                                else
                                {
                                    if (queryClient is IDisposable disposable)
                                    {
                                        disposable.Dispose();
                                    }
                                }
                            }
                        }
                    }
                }

                Dictionary <string, HashSet <string> > relayRegisterTypes = null;
                if (relayRegister != null)
                {
                    relayRegisterTypes = new Dictionary <string, HashSet <string> >();
                }

                if (commandServer != null)
                {
                    commandServer.Open();
                    if (relayRegister != null)
                    {
                        var commandTypes = commandServer.GetCommandTypes().Select(x => x.GetNiceName()).ToArray();
                        if (!relayRegisterTypes.TryGetValue(commandServer.ConnectionString, out HashSet <string> relayTypes))
                        {
                            relayTypes = new HashSet <string>();
                            relayRegisterTypes.Add(commandServer.ConnectionString, relayTypes);
                        }
                        foreach (var type in commandTypes)
                        {
                            relayTypes.Add(type);
                        }
                    }
                }
                if (eventServer != null)
                {
                    eventServer.Open();
                    if (relayRegister != null)
                    {
                        var eventTypes = eventServer.GetEventTypes().Select(x => x.GetNiceName()).ToArray();
                        if (!relayRegisterTypes.TryGetValue(eventServer.ConnectionString, out HashSet <string> relayTypes))
                        {
                            relayTypes = new HashSet <string>();
                            relayRegisterTypes.Add(eventServer.ConnectionString, relayTypes);
                        }
                        foreach (var type in eventTypes)
                        {
                            relayTypes.Add(type);
                        }
                    }
                }
                if (queryServer != null)
                {
                    queryServer.Open();
                    if (relayRegister != null)
                    {
                        var queryTypes = queryServer.GetInterfaceTypes().Select(x => x.GetNiceName()).ToArray();
                        if (!relayRegisterTypes.TryGetValue(queryServer.ConnectionString, out HashSet <string> relayTypes))
                        {
                            relayTypes = new HashSet <string>();
                            relayRegisterTypes.Add(queryServer.ConnectionString, relayTypes);
                        }
                        foreach (var type in queryTypes)
                        {
                            relayTypes.Add(type);
                        }
                    }
                }

                if (relayRegister != null)
                {
                    foreach (var group in relayRegisterTypes)
                    {
                        relayRegister.Register(group.Key, group.Value.ToArray());
                    }
                }

                if (serverSetting.InstantiateTypes != null && serverSetting.InstantiateTypes.Length > 0)
                {
                    foreach (var instantiation in serverSetting.InstantiateTypes)
                    {
                        try
                        {
                            var type     = Discovery.GetTypeFromName(instantiation);
                            var instance = Activator.CreateInstance(type);
                            instanciations.Add(instance);
                        }
                        catch (Exception ex)
                        {
                            _ = Log.ErrorAsync($"Failed to instantiate {instantiation}", ex);
                        }
                    }
                }
            }
        }
 public QueryIndexManager(IQueryClient queryClient)
 {
     _queryClient = queryClient;
 }
 public QueryIndexes(IQueryClient queryClient)
 {
     _queryClient = queryClient;
 }
Exemplo n.º 25
0
        public void Run()
        {
            _addonManager.Addons.ForEach(addon => Logger.Ok($"({addon.Name}) : Loaded"));
            Logger.Ok("Registering notifications");
            var notifications = new NotificationHub();

            notifications.UnknownNotificationReceived.Triggered += UnknownNotificationReceived_Triggered;
            _addonManager.RegisterNotifications(notifications);


            QueryClient = new QueryClient(notificationHub: notifications, keepAliveInterval: TimeSpan.FromSeconds(30),
                                          host: Config.Server.Host, port: Config.Server.QueryPort);
            QueryClient.BanDetected      += Client_BanDetected;
            QueryClient.ConnectionClosed += Client_ConnectionClosed;
            Connect(QueryClient);
            Logger.Ok(
                $"Query login : {!new LoginCommand(Config.Server.Login, Config.Server.Password).Execute(QueryClient).IsErroneous}");
            Logger.Info(
                $"Switch to server with port {Config.Server.ServerPort} : {!new UseCommand(Config.Server.ServerPort).Execute(QueryClient).IsErroneous}");
            new ClientUpdateCommand(new ClientModification {
                Nickname = Config.Bot.Name
            }).ExecuteAsync(QueryClient);
            Logger.Ok(
                $"Notifications [Server] : {!new ServerNotifyRegisterCommand(ServerNotifyRegisterEvent.Server, 0).Execute(QueryClient).IsErroneous}");
            Logger.Ok(
                $"Notifications [Channel] : {!new ServerNotifyRegisterCommand(ServerNotifyRegisterEvent.Channel, 0).Execute(QueryClient).IsErroneous}");
            Logger.Ok(
                $"Notifications [Channel-Text] :  {!new ServerNotifyRegisterCommand(ServerNotifyRegisterEvent.TextChannel, 1).Execute(QueryClient).IsErroneous}");
            Logger.Ok(
                $"Notifications [Server-Text] : {!new ServerNotifyRegisterCommand(ServerNotifyRegisterEvent.TextServer).Execute(QueryClient).IsErroneous}");
            Logger.Ok(
                $"Notifications [Private-Text] : {!new ServerNotifyRegisterCommand(ServerNotifyRegisterEvent.TextPrivate).Execute(QueryClient).IsErroneous}");
            Logger.Ok(
                $"Notifications [TokenUsed] : {!new ServerNotifyRegisterCommand(ServerNotifyRegisterEvent.TokenUsed).Execute(QueryClient).IsErroneous}");

            Logger.Info("Type a command or press [ENTER] to exit");


            do
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.Write($"<{Config.Server.Login}:{QueryClient.Host}:{QueryClient.Port}> Send: ");
                Console.ResetColor();

                var commandText = Console.ReadLine();

                if (commandText != null && commandText.Length == 0)
                {
                    new LogoutCommand().Execute(QueryClient);
                    break;
                }

                var response = QueryClient.Send(commandText);
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.Write("Response: ");
                Console.ResetColor();
                Console.WriteLine(response);
            } while (QueryClient.Connected);

            Console.WriteLine("Exiting now...");
        }
Exemplo n.º 26
0
 private static void Connect(IQueryClient client)
 {
     client.Connect();
 }
 public void HandleResponse(IQueryClient queryClient, string responseText)
 {
 }
Exemplo n.º 28
0
 void INotificationHandler.HandleResponse(IQueryClient queryClient, string responseText)
 {
     Triggered?.Invoke(queryClient, new ChannelCreatedEventArgs(CommandParameterGroupList.Parse(responseText)));
 }
Exemplo n.º 29
0
 public QueryIndexManager(IQueryClient queryClient, ILogger <QueryIndexManager> logger, IRedactor redactor)
 {
     _queryClient = queryClient ?? throw new ArgumentNullException(nameof(queryClient));
     _logger      = logger ?? throw new ArgumentNullException(nameof(logger));
     _redactor    = redactor ?? throw new ArgumentNullException(nameof(redactor));
 }
Exemplo n.º 30
0
 void INotificationHub.HandleRawNotification(IQueryClient queryClient, string notificationName, string responseText)
 {
     // run the handling on a task to not block message handling in queryclient
     Task.Run(() => HandleRawNotificationAsync(queryClient, notificationName, responseText));
 }