nats-io / stan.net

The official NATS .NET C# Streaming Client
Apache License 2.0
138 stars 41 forks source link

Not owned NATS connection is closed if timeout occurs during ConnectRequest #181

Closed dorny closed 4 years ago

dorny commented 4 years ago

I had encountered an unexpected behavior. NATS connection provided via StanOptions.NatsConn is closed by STAN Connection constructor if the NATSTimeoutException is thrown during ConnectRequest. It can be easily reproduced by using wrong (non-matching) cluster ID. It may also happen when NATS server is already started but NATS.Streaming server is still starting and misses the connection request.

There are only 3 occurrences of calls to close the underlying NATS conneciton. Two of them are behind if (ncOwned) condition. Only this one doesn't check if the connection is owned or not.

Here is the code causing the issue:

Msg cr;
try
{
    cr = nc.Request(discoverSubject,
        ProtocolSerializer.marshal(req),
        opts.ConnectTimeout);
}
catch (NATSTimeoutException)
{
    protoUnsubscribe();
    nc?.Close();
    nc?.Dispose();
    throw new StanConnectRequestTimeoutException(
        string.Format("No response from a streaming server with a cluster ID of '{0}'", stanClusterID));
}

I will submit PR fixing this.

ColinSullivan1 commented 4 years ago

Thanks!