Add WebSocketOptions.Timeout to ClientWebSocket
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.
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: |
|
| Milestone: | - |
Related: https://github.com/dotnet/aspnetcore/issues/24614
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.
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).
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.
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.
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)
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.
Note: there's another ask for this feature #60620
@gdalsnes @aroman can you please upvote top post? That will help us track number of people who need this behavior. Thanks!
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).
I've updated the root description with the API proposal
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?)
@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.
@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?
WebSocketAcceptContext would likely need a new property, something like KeepAliveTimeout. I can help out if this feature gets added.
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
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.
Triage: given that the customer ask is high, and it should be relatively easy to implement, optimistically putting it to 9.0.
@pavelsavara do you know whether browser websocket supports sending keep-alives (ping/pong frames)?