Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ws] Fix debugging web socket JS code + add test #99240

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,27 @@ await socket.CloseAsync(
{
await Task.Delay(5000);
}
else if (receivedMessage == ".shutdownAfterTwoMessages")
{
byte[] buffer = new byte[1024];
string message1 = $"{receivedMessage} 1 {DateTime.Now.ToString("HH:mm:ss")}";
buffer = System.Text.Encoding.UTF8.GetBytes(message1);
await socket.SendAsync(
new ArraySegment<byte>(buffer, 0, message1.Length),
WebSocketMessageType.Text,
true,
CancellationToken.None);
await Task.Delay(1990); // try to sync with receive request from the client: 1.9k is too little, 2k too much
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the tricky part. What would happen if the wait was not there at all ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would have sent one after another, so it would be event order:

  • connect, ask for receive 1, send1, send2, ask for receive 2.

Adding this delay we are on the boarder of the above scenario and the below:

  • connect, ask for receive 1, send1, ask for receive 2, send 2.

By "on the boarder" I mean it's random, sometimes we fall into 1st scenario, sometimes into the 2nd.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ask for receive 2 should have no impact on the JS side order of WS events and JS side buffering, right ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we trying to get into situation that "ws.state == CLOSE" but the on_message for the second message was not called yet ?

If that's possible, the current implementation is wrong. But I need to see it before I can believe it 🔍

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The time when we ask for receive seems important, when using the debugger, we enter the receiving method before we got "on_message_sent" event but after the WS is closed. That's why I was trying to time it as close in time to closing and sending actions as possible.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anyway, we could try to stop using ws.state for this and rely on the on_close event

Copy link
Member Author

@ilonatommy ilonatommy Mar 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing the if (readyState == WebSocket.CLOSED) block of code from ws_wasm_receive eliminates the exception during debugging.

Copy link
Member Author

@ilonatommy ilonatommy Mar 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it mean that

     const readyState = ws.readyState;
     if (readyState == WebSocket.CLOSED) {
         const receive_status_ptr = ws[wasm_ws_receive_status_ptr];
         setI32(receive_status_ptr, 0); // count
         setI32(<any>receive_status_ptr + 4, 2); // type:close
         setI32(<any>receive_status_ptr + 8, 1);// end_of_message: true
         return resolvedPromise();
     }

is redundant? Managed code does no need setting these bits?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's good question. on_close has similar code and would deliver the resolution if we deleted this.

Copy link
Member Author

@ilonatommy ilonatommy Mar 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a difference between the demo and the tests: demo does not close the socket, only dispose of it and in case the socket was opened without using CloseAsync(), the WebSocket connection will be abruptly terminated. This termination will occur without following the WebSocket protocol's normal closure handshake, potentially leading to unexpected behavior or errors on the client side. Upon correcting the demo code to close the socket (like our tests do), I cannot reproduce the issue with "lost messages". The current, working version of code has the if (readyState == WebSocket.CLOSED) block removed.


string message2 = $"{receivedMessage} 2 {DateTime.Now.ToString("HH:mm:ss")}";
buffer = System.Text.Encoding.UTF8.GetBytes(message2);
await socket.SendAsync(
new ArraySegment<byte>(buffer, 0, message2.Length),
WebSocketMessageType.Text,
true,
CancellationToken.None);
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, receivedMessage, CancellationToken.None);
}
else if (socket.State == WebSocketState.Open)
{
sendMessage = true;
Expand Down
29 changes: 29 additions & 0 deletions src/libraries/System.Net.WebSockets.Client/tests/CloseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,35 @@ await cws.SendAsync(
}
}


[ActiveIssue("https://github.com/dotnet/runtime/issues/28957", typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ServerInitiated_CanSendRepeatedly(Uri server)
{
using (ClientWebSocket cws = await GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);

await cws.SendAsync(
WebSocketData.GetBufferFromText(".shutdownAfterTwoMessages"),
WebSocketMessageType.Text,
true,
cts.Token);

var recvBuffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(recvBuffer, cts.Token);
var message = Encoding.UTF8.GetString(recvBuffer.ToArray(), 0, recvResult.Count);
Assert.Contains(".shutdownAfterTwoMessages 1", message);

await Task.Delay(2000);

recvResult = await cws.ReceiveAsync(recvBuffer, cts.Token);
message = Encoding.UTF8.GetString(recvBuffer.ToArray(), 0, recvResult.Count);
Assert.Contains(".shutdownAfterTwoMessages 2", message);
}
}

[OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))]
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_CloseDescriptionIsNull_Success(Uri server)
Expand Down
9 changes: 0 additions & 9 deletions src/mono/browser/runtime/web-socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,15 +219,6 @@ export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buf
return resolvedPromise();
}

const readyState = ws.readyState;
if (readyState == WebSocket.CLOSED) {
const receive_status_ptr = ws[wasm_ws_receive_status_ptr];
setI32(receive_status_ptr, 0); // count
setI32(<any>receive_status_ptr + 4, 2); // type:close
setI32(<any>receive_status_ptr + 8, 1);// end_of_message: true
return resolvedPromise();
}

const { promise, promise_control } = createPromiseController<void>();
const receive_promise_control = promise_control as ReceivePromiseControl;
receive_promise_control.buffer_ptr = buffer_ptr;
Expand Down
Loading