zeromq / netmq

A 100% native C# implementation of ZeroMQ for .NET
Other
2.93k stars 744 forks source link

"Closed" callback is called after the "Connected" callback when changing socket address. #1084

Open Satris404 opened 4 months ago

Satris404 commented 4 months ago

Environment

NetMQ Version: 4.0.1.11
Operating System: Windows
.NET Version: .NET 7.0

Expected behaviour

Situation: The socket tries to connect to a server given an erroneous address (the address is valid, but points to the wrong IP). The socket retries to connect periodically. A NetMQMonitor monitors the connection, each events are subscribed Action: I disconnect the socket from the address, then connect given a new address of the actual ZMQ server. Expected: The Connected callback shall be the last callback event happening chornologically

Actual behaviour

The "Closed" callback is called just after the "Connected" callback is called. This leads to undesired state, where we think that the socket is closed when it is actually connected.

Steps to reproduce the behaviour

   public PubSubSocketListenerHostedService(
        ILogger<LeddarVisionPubSubSocketListenerHostedService> logger
    )
    {
        this._logger = logger;
        this._subSocket = new SubscriberSocket();
        this._poller = new NetMQPoller();
        this._connectionMonitor = new NetMQMonitor(
            this._subSocket,
            $"inproc://sub.inproc",
            SocketEvents.All
        );
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        this._subSocket.Options.ReceiveHighWatermark = 1000;
        this._subSocket.Options.ReconnectIntervalMax = new TimeSpan(0, 0, 5); // Set reconnect interval to 5 seconds
        this._connectionMonitor.Connected += this.OnConnected;
        this._connectionMonitor.Disconnected += this.OnDisconnected;
        this._connectionMonitor.ConnectDelayed += this.OnConnectDelayed;
        this._connectionMonitor.ConnectRetried += this.OnConnectRetried;
        this._connectionMonitor.Closed += this.OnListenClose;
        this._connectionMonitor.AcceptFailed += this.OnAcceptFailed;
        this._connectionMonitor.CloseFailed += this.OnCloseFailed;
        this._connectionMonitor.BindFailed += this.OnBindFailed;
        this._connectionMonitor.AttachToPoller(this._poller);
        this._subSocket.Connect(this.Url);
        this._subSocket.ReceiveReady += this.OnReceiveReady;
        this._poller.Add(this._subSocket);
        this._poller.RunAsync();

        return Task.CompletedTask;
    }

private void UpdateRemoteConnection(string url)
    {
        if (!this._subSocket.IsDisposed)
        {
            var successfullyDisconnected = false;
            try
            {
                this._subSocket.Disconnect(this.Url);
                successfullyDisconnected = true;
            }
            catch (Exception exception)
            {
                this._logger.LogWarning("An error occured while trying to disconnect from {}. {}",
                    this.Url, exception);
            }

            if (successfullyDisconnected)
            {
                try
                {
                    this._logger.LogInformation("Initiate connection to {}", url);
                    this._subSocket.Connect(url);
                    this.Url = url;
                }
                catch (Exception exception)
                {
                    this._logger.LogWarning("An error occured while trying to connect to {}. {}",
                        url, exception);
                }
            }
        }
    }

Temporary fix

private void UpdateRemoteConnection(string url)
    {
        if (!this._subSocket.IsDisposed)
        {
            var successfullyDisconnected = false;
            try
            {
                this._subSocket.Disconnect(this.Url);
                successfullyDisconnected = true;
            }
            catch (Exception exception)
            {
                this._logger.LogWarning("An error occured while trying to disconnect from {}. {}",
                    this.Url, exception);
            }
            this._connectionMonitor.Closed -= this.OnListenClose;
            this._connectionMonitor.ConnectRetried -= this.OnConnectRetried;
            this._connectionMonitor.Disconnected -= this.OnDisconnected;
            if (successfullyDisconnected)
            {
                try
                {
                    this._logger.LogInformation("Initiate connection to {}", url);
                    this._subSocket.Connect(url);
                    this.Url = url;
                    Task.Delay(500)
                        .ContinueWith(_ =>
                        {
                            this._connectionMonitor.Closed += this.OnListenClose;
                            this._connectionMonitor.ConnectRetried += this.OnConnectRetried;
                            this._connectionMonitor.Disconnected += this.OnDisconnected;
                        });
                }
                catch (Exception exception)
                {
                    this._logger.LogWarning("An error occured while trying to connect to {}. {}",
                        url, exception);
                }
            }
        }
    }

*** Note this behavior was found on a computer, but could not be reproduced on a different setup (the exact same code was running on both computers)