Ejemplo n.º 1
0
        public Task OnDisconnectedAsync(IConnectionContext connection)
        {
            _connections.Remove(connection);

            var tasks = new List <Task>();

            var connectionChannel = _channels.Connection(connection.ConnectionId);

            RedisLog.Unsubscribe(_logger, connectionChannel);
            tasks.Add(_bus.UnsubscribeAsync(connectionChannel));

            var feature    = connection.Features.Get <IRedisFeature>();
            var groupNames = feature.Groups;

            if (groupNames != null)
            {
                // Copy the groups to an array here because they get removed from this collection
                // in RemoveFromGroupAsync
                foreach (var group in groupNames.ToArray())
                {
                    // Use RemoveGroupAsyncCore because the connection is local and we don't want to
                    // accidentally go to other servers with our remove request.
                    tasks.Add(RemoveGroupAsyncCore(connection, group));
                }
            }

            if (!string.IsNullOrEmpty(connection.UserIdentifier))
            {
                tasks.Add(RemoveUserAsync(connection));
            }

            return(Task.WhenAll(tasks));
        }
Ejemplo n.º 2
0
        private Task SubscribeToUser(IConnectionContext connection)
        {
            var userChannel = _channels.User(connection.UserIdentifier);

            return(_users.AddSubscriptionAsync(userChannel, connection, async(channelName, subscriptions) =>
            {
                RedisLog.Subscribing(_logger, channelName);
                var channel = await _bus.SubscribeAsync(channelName);
                channel.OnMessage(async channelMessage =>
                {
                    try
                    {
                        var invocation = _protocol.ReadInvocation((byte[])channelMessage.Message);

                        var tasks = new List <Task>();
                        foreach (var userConnection in subscriptions)
                        {
                            tasks.Add(userConnection.WriteAsync(invocation.Message, CancellationToken.None));
                        }

                        await Task.WhenAll(tasks);
                    }
                    catch (Exception ex)
                    {
                        RedisLog.FailedWritingMessage(_logger, ex);
                    }
                });
            }));
        }
Ejemplo n.º 3
0
        private async Task SubscribeToGroupAsync(string groupChannel, ConnectionStore groupConnections)
        {
            RedisLog.Subscribing(_logger, groupChannel);
            var channel = await _bus.SubscribeAsync(groupChannel);

            channel.OnMessage(async(channelMessage) =>
            {
                try
                {
                    var invocation = _protocol.ReadInvocation((byte[])channelMessage.Message);

                    var tasks = new List <Task>();
                    foreach (var groupConnection in groupConnections)
                    {
                        if (invocation.ExcludedConnectionIds?.Contains(groupConnection.ConnectionId) == true)
                        {
                            continue;
                        }

                        tasks.Add(groupConnection.WriteAsync(invocation.Message, CancellationToken.None));
                    }

                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    RedisLog.FailedWritingMessage(_logger, ex);
                }
            });
        }
Ejemplo n.º 4
0
        private async Task SubscribeToAll()
        {
            RedisLog.Subscribing(_logger, _channels.All);
            var channel = await _bus.SubscribeAsync(_channels.All);

            channel.OnMessage(async channelMessage =>
            {
                try
                {
                    RedisLog.ReceivedFromChannel(_logger, _channels.All);

                    var invocation = _protocol.ReadInvocation((byte[])channelMessage.Message);

                    var tasks = new List <Task>(_connections.Count);

                    foreach (var connection in _connections)
                    {
                        if (invocation.ExcludedConnectionIds == null || !invocation.ExcludedConnectionIds.Contains(connection.ConnectionId))
                        {
                            tasks.Add(connection.WriteAsync(invocation.Message, CancellationToken.None));
                        }
                    }

                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    RedisLog.FailedWritingMessage(_logger, ex);
                }
            });
        }
Ejemplo n.º 5
0
        private async Task PublishAsync(string channel, byte[] payload)
        {
            await EnsureRedisServerConnection();

            RedisLog.PublishToChannel(_logger, channel);
            await _bus.PublishAsync(channel, payload);
        }
Ejemplo n.º 6
0
        private async Task EnsureRedisServerConnection()
        {
            if (_redisServerConnection == null)
            {
                await _connectionLock.WaitAsync();

                try
                {
                    if (_redisServerConnection == null)
                    {
                        var writer = new LoggerTextWriter(_logger);
                        _redisServerConnection = await _options.ConnectAsync(writer);

                        _bus = _redisServerConnection.GetSubscriber();

                        _redisServerConnection.ConnectionRestored += (_, e) =>
                        {
                            // We use the subscription connection type
                            // Ignore messages from the interactive connection (avoids duplicates)
                            if (e.ConnectionType == ConnectionType.Interactive)
                            {
                                return;
                            }

                            RedisLog.ConnectionRestored(_logger);
                        };

                        _redisServerConnection.ConnectionFailed += (_, e) =>
                        {
                            // We use the subscription connection type
                            // Ignore messages from the interactive connection (avoids duplicates)
                            if (e.ConnectionType == ConnectionType.Interactive)
                            {
                                return;
                            }

                            RedisLog.ConnectionFailed(_logger, e.Exception);
                        };

                        if (_redisServerConnection.IsConnected)
                        {
                            RedisLog.Connected(_logger);
                        }
                        else
                        {
                            RedisLog.NotConnected(_logger);
                        }

                        await SubscribeToAll();
                        await SubscribeToGroupManagementChannel();
                        await SubscribeToAckChannel();
                    }
                }
                finally
                {
                    _connectionLock.Release();
                }
            }
        }
Ejemplo n.º 7
0
        private Task RemoveUserAsync(IConnectionContext connection)
        {
            var userChannel = _channels.User(connection.UserIdentifier);

            return(_users.RemoveSubscriptionAsync(userChannel, connection, channelName =>
            {
                RedisLog.Unsubscribe(_logger, channelName);
                return _bus.UnsubscribeAsync(channelName);
            }));
        }
Ejemplo n.º 8
0
        public RedisConnectionLifetimeManager(ILogger <RedisConnectionLifetimeManager> logger,
                                              IOptions <RedisOptions> options)
        {
            _logger     = logger;
            _options    = options.Value;
            _ackHandler = new AckHandler();
            _channels   = new RedisChannels("RedisConnectionLifetimeManager");
            _protocol   = new RedisProtocol();

            RedisLog.ConnectingToEndpoints(_logger, options.Value.Configuration.EndPoints, _serverName);
            _ = EnsureRedisServerConnection();
        }
Ejemplo n.º 9
0
        private async Task SubscribeToConnection(IConnectionContext connection)
        {
            var connectionChannel = _channels.Connection(connection.ConnectionId);

            RedisLog.Subscribing(_logger, connectionChannel);
            var channel = await _bus.SubscribeAsync(connectionChannel);

            channel.OnMessage(channelMessage =>
            {
                var invocation = _protocol.ReadInvocation((byte[])channelMessage.Message);
                return(connection.WriteAsync(invocation.Message, CancellationToken.None));
            });
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This takes <see cref="HubConnectionContext"/> because we want to remove the connection from the
        /// _connections list in OnDisconnectedAsync and still be able to remove groups with this method.
        /// </summary>
        private async Task RemoveGroupAsyncCore(IConnectionContext connection, string groupName)
        {
            var groupChannel = _channels.Group(groupName);

            await _groups.RemoveSubscriptionAsync(groupChannel, connection, channelName =>
            {
                RedisLog.Unsubscribe(_logger, channelName);
                return(_bus.UnsubscribeAsync(channelName));
            });

            var feature    = connection.Features.Get <IRedisFeature>();
            var groupNames = feature.Groups;

            if (groupNames != null)
            {
                lock (groupNames)
                {
                    groupNames.Remove(groupName);
                }
            }
        }
Ejemplo n.º 11
0
        private async Task SubscribeToGroupManagementChannel()
        {
            var channel = await _bus.SubscribeAsync(_channels.GroupManagement);

            channel.OnMessage(async channelMessage =>
            {
                try
                {
                    var groupMessage = _protocol.ReadGroupCommand((byte[])channelMessage.Message);

                    var connection = _connections[groupMessage.ConnectionId];
                    if (connection == null)
                    {
                        // user not on this server
                        return;
                    }

                    if (groupMessage.Action == GroupAction.Remove)
                    {
                        await RemoveGroupAsyncCore(connection, groupMessage.GroupName);
                    }

                    if (groupMessage.Action == GroupAction.Add)
                    {
                        await AddGroupAsyncCore(connection, groupMessage.GroupName);
                    }

                    // Send an ack to the server that sent the original command.
                    await PublishAsync(_channels.Ack(groupMessage.ServerName), _protocol.WriteAck(groupMessage.Id));
                }
                catch (Exception ex)
                {
                    RedisLog.InternalMessageFailed(_logger, ex);
                }
            });
        }
Ejemplo n.º 12
0
 public override void WriteLine(string value)
 {
     RedisLog.ConnectionMultiplexerMessage(_logger, value);
 }