runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Add WebSocketOptions.Timeout to ClientWebSocket

Open bjornen77 opened this issue 5 years ago • 39 comments

Edited by @CarnaViire

Justification

This API allows the users to identify and close idle WebSocket connections without having to rely on the TCP KeepAlive timeout, which can be way too big (e.g. ~15 min on Linux), and can be impossible or very hard to configure.

// see the original issue in the end of the post

API Proposal

namespace System.Net.WebSockets;

// used to create a base WebSocket (ManagedWebSocket) instance
public class WebSocketCreationOptions
{
    // existing
    //public TimeSpan KeepAliveInterval { get; set; } // default: infinite (off)

    // new
    public TimeSpan KeepAliveTimeout { get; set; } = Timeout.InfiniteTimeSpan;

    // ...
}

// used to configure a ClientWebSocket instance
public class ClientWebSocketOptions
{
    // existing
    //[UnsupportedOSPlatform("browser")]
    //public TimeSpan KeepAliveInterval { get; set; } // default: 30s

    // new
    [UnsupportedOSPlatform("browser")]
    public TimeSpan KeepAliveTimeout { get; set; } = Timeout.InfiniteTimeSpan;

    // ...
}

Usage

For ClientWebSocket:

var ws = new ClientWebSocket();
ws.Options.KeepAliveTimeout = TimeSpan.FromSeconds(10);
await ws.ConnectAsync(uri, cts.Token);

For ManagedWebSocket:

var options = new WebSocketCreationOptions()
{
    KeepAliveInterval = WebSocket.DefaultKeepAliveInterval,
    KeepAliveTimeout = TimeSpan.FromSeconds(10)
};
var ws = WebSocket.CreateFromStream(stream, options);

Notes on behavior

Timeout.InfiniteTimeSpan or TimeSpan.Zero would disable the timeout logic and fall back to the existing "unsolicited" Pong keep-alive (per understanding in https://github.com/dotnet/runtime/issues/35473#issuecomment-620726903 we cannot send Pings without waiting for the reply)

Any other positive timeout value would turn on Ping-Pong logic; we will be sending Pings instead of Pongs and track whether we've received Pongs in time; if not, the connection is treated as stale and aborted. The behavior and implementation should be similar to HTTP/2 KeepAlivePingTimeout.

Alternative Naming

We could name the new property KeepAlivePingTimeout. This will "break" it's similarity to KeepAliveInterval, but it might help highlight that Pings, not Pongs, are being sent (if we care enough about this distinction).

namespace System.Net.WebSockets;

public class WebSocketCreationOptions
{
    //public TimeSpan KeepAliveInterval { get; set; } // existing
    public TimeSpan KeepAlivePingTimeout { get; set; } // new

    // ...
}

public class ClientWebSocketOptions
{
    //public TimeSpan KeepAliveInterval { get; set; } // existing
    public TimeSpan KeepAlivePingTimeout { get; set; } // new

    // ...
}

Existing API shape for other keep-alives

For comparison:

// HTTP/2 in runtime:
namespace System.Net.Http;
public class SocketsHttpHandler
{
    public TimeSpan KeepAlivePingDelay { get; set; } // default: infinite (off)
    public TimeSpan KeepAlivePingTimeout { get; set; } // default: 20s (N/A when delay=inf)
    public HttpKeepAlivePingPolicy KeepAlivePingPolicy { get; set; } // default: Always
    // ...
}

// HTTP/2 in Kestrel:
namespace Microsoft.AspNetCore.Server.Kestrel.Core;
public class Http2Limits
{
    public TimeSpan KeepAlivePingDelay { get; set; } // default: infinite (off)
    public TimeSpan KeepAlivePingTimeout { get; set; } // default: 20s (N/A when delay=inf)
    // ...
}

// Sockets in runtime:
namespace System.Net.Sockets;
public enum SocketOptionName
{
    TcpKeepAliveInterval, // between probe retries, if no answer received
    TcpKeepAliveRetryCount, // probe retries before deemed idle, if no answer received
    TcpKeepAliveTime, // before the first probe, after the last received byte
    // ...
}

Original issue by @bjornen77

I think that adding a WebSocketOptions.Timeout property would be a good thing.

Today, the ClientWebSocket is closed when the TCP Retransmission times out(if the connection to the server drops for some reason). This timeout seems to be different on Windows and Linux. By default, on Windows it takes about 21 seconds and on Linux it takes about 15 minutes before the WebSocket is closed. It would be good if we could have a separate Timeout setting, so that we get the same behavior regardless of the platform. And also that this could be configured by the application without having to modify the TCP Timeout settings in the OS... The websocket should still be disconnected if the OS TCP Timeout is reached.

The ClientWebSocket today only sends "Pong" to the server, and therefore it does not wait for a "Pong" response to arrive. I think that the ClientWebSocket shall send a "Ping" instead, and then verify that a "Pong" is received within the Timeout set. If not received, the connection shall be closed. Or at least it should expose the "received "Pong" message in the WebSocketReceiveResult.MessageType. It would be good if an received "Ping" message from a server is also exposed. Then the application could use these Ping/Pong message types to implement its own timeout logic.

bjornen77 avatar Feb 24 '21 23:02 bjornen77

Tagging subscribers to this area: @dotnet/ncl See info in area-owners.md if you want to be subscribed.

Issue Details

I think that adding a WebSocketOptions.Timeout property would be a good thing.

Today, the ClientWebSocket is closed when the TCP Retransmission times out. This timeout seems to be different on Windows and Linux. By default, on Windows it takes about 21 seconds and on Linux it takes about 15 minutes before the WebSocket is closed. It would be good if we could have a separate Timeout setting, so that we get the same behavior regardless of the platform.

The ClientWebSocket today only sends "Pong" to the server, and therefore it does not wait for a "Pong" response to arrive. I think that the ClientWebSocket shall send a "Ping" instead, and then verify that a "Pong" is received within the Timeout set. If not received, the connection shall be closed. Or at least it should expose the "Ping" and "Pong" messages in the WebSocketReceiveResult.MessageType. Then the application could use these Ping/Pong message types to implement its own timeout logic.

Author: bjornen77
Assignees: -
Labels:

area-System.Net, untriaged

Milestone: -

ghost avatar Feb 24 '21 23:02 ghost

Related: https://github.com/dotnet/aspnetcore/issues/24614

bjornen77 avatar Feb 24 '21 23:02 bjornen77

This is a duplicate of: https://github.com/dotnet/runtime/issues/35473 We expose KeepAliveInterval but we use it only for sending Pongs to keep the connection open: https://github.com/dotnet/runtime/blob/b121bcacec60f10b316b25eb9d0b7113599bc508/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs#L576-L579

We might revisit the original decision to not to send Pings.

ManickaP avatar Feb 25 '21 12:02 ManickaP

I think it should be revisited. Today's implementation relies on the OS TCP/IP timeout setting to be able to determine when the WebSocket has been disconnected. It is not always wanted to change this setting in the OS as it effect all applications running there.

Also. this OS setting differs by default between Windows and Linux. By default on Linux it takes about 15 minutes before the client realizes that the server is not there anymore. I think that it would be good to be able to set a timeout value on the ClientWebSocket itself(and use the PING/PONG frames internally to detect if a timeout occurs). Exposing the PONG messages is not needed if this is handled internally(preferred).

bjornen77 avatar Feb 25 '21 13:02 bjornen77

Triage: we are open to adding proper ping/pong sending. At the moment, there's only this one issue asking for it so we'll leave it to future. We should consider starting with fixed timeout before adding API.

ManickaP avatar Feb 25 '21 17:02 ManickaP

If adding a new Timeout setting/property maybe the following would be something to consider when implementing:

  • Timeout value is set to <=0, the old behavior is used, where only PONGs are sent.
  • Timeout value is set to > 0, the new PING/PONG sequence, with timeout detection is used.

bjornen77 avatar Feb 25 '21 19:02 bjornen77

Triage: we are open to adding proper ping/pong sending. At the moment, there's only this one issue asking for it so we'll leave it to future.

Not so. Issue https://github.com/dotnet/aspnetcore/issues/24614 is already asking for the same (and duplicate https://github.com/dotnet/aspnetcore/issues/26117)

osexpert avatar Feb 26 '21 12:02 osexpert

Strong +1 for this issue. This is an important feature for applications like games where detecting a broken connection quickly is important for user experience. The WebSocket API does not expose the ability to send ping or pong messages, so there isn't even really a way to add this functionality in our applications without creating our own works-like ping/pong messages (which aren't really ping/pong messages but regular websocket messages).

Just one point of clarification in the original issue — OP mentions that the current implementation only sends pong, rather than ping. I don't think that's true, from what I can see in ManagedWebSocket:518. I think the issue is simply that the implementation doesn't wait for a pong in response to the ping.

The WebSocket RFC does not explicitly specify that clients should disconnect in the case a pong is not received in response to a ping within a certain timeframe. I think this would be a good thing to do though, as a user-configurable option. It should probably be default-off, so the change doesn't impact any applications which are somehow depending on very long retry times. Just adding an extra WebSocketOptions for this as OP suggests is the right approach IMHO.

aroman avatar Jun 24 '21 16:06 aroman

Note: there's another ask for this feature #60620

CarnaViire avatar Oct 19 '21 14:10 CarnaViire

@gdalsnes @aroman can you please upvote top post? That will help us track number of people who need this behavior. Thanks!

karelz avatar Nov 01 '21 14:11 karelz

I guess SignalR uses its own pingpong, and is covering over for this flaw for most use cases? But I use it with vs-streamjsonrpc and ended up implementing my own pingpong, and used 99.9% time on that and the rest on actual work... My testing involved killing processes, pulling network cables, supending/resuming/killing VM's, "pulling" network "cables" within VM's etc. I easily got into situations with infinite hang (waited over night).

osexpert avatar Nov 01 '21 15:11 osexpert

I've updated the root description with the API proposal

CarnaViire avatar Nov 01 '21 20:11 CarnaViire

I've updated the root description with the API proposal

But will this cover aspnetcore websocket as well? It should also have the same timeout option, else it can hang forever and stall request pipelines (potentional DOS problem?)

osexpert avatar Nov 01 '21 20:11 osexpert

@gdalsnes what do you mean by "aspnetcore WebSocket"? ASP.NET WebSocket is based on our implementation to our best knowledge. Unless there is some wrapper around our APIs, all should be good. We do not restrict what frameworks/apps above us do.

karelz avatar Nov 01 '21 20:11 karelz

@gdalsnes good point. This will need an additional API from ASP.NET Core side as well. I suspect it should be added to ExtendedWebSocketAcceptContext the way WebSocket compression was added... @BrennanConroy will you be able to help with ASP.NET Core side please?

CarnaViire avatar Nov 01 '21 20:11 CarnaViire

WebSocketAcceptContext would likely need a new property, something like KeepAliveTimeout. I can help out if this feature gets added.

BrennanConroy avatar Nov 01 '21 20:11 BrennanConroy

We need to ping from client and server every few seconds to make sure connection is still alive and restart asap if needed. Since this is not possible with official ClientWebSocket, I use modified websocket-sharp for now

michaldobrodenka avatar May 16 '23 18:05 michaldobrodenka

I would also like to see this implemented. Our setup is running a websoket server with lots of embedded devices as clients. We run a standardized protocol based on websocket and therefore cannot implement our own ping mechanism or use signalR. It's important since if you run linux for your servers it will take about 15 min for it to detect a disconnect as the default TCP RTO setting in linux.

JohnMaddison avatar Jan 11 '24 20:01 JohnMaddison

Triage: given that the customer ask is high, and it should be relatively easy to implement, optimistically putting it to 9.0.

CarnaViire avatar Jan 15 '24 16:01 CarnaViire

@pavelsavara do you know whether browser websocket supports sending keep-alives (ping/pong frames)?

CarnaViire avatar Jan 18 '24 17:01 CarnaViire