-
Notifications
You must be signed in to change notification settings - Fork 1.3k
CSHARP-3662: MongoClientSettings.SocketTimeout does not work for values under 500ms on Windows for sync code #1690
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
base: main
Are you sure you want to change the base?
Changes from 3 commits
e60210b
ea9d7d1
f276888
e7095f9
fe81697
8f3f0ac
940c764
fdd35f5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -333,14 +333,15 @@ private IByteBuffer ReceiveBuffer(CancellationToken cancellationToken) | |
try | ||
{ | ||
var messageSizeBytes = new byte[4]; | ||
_stream.ReadBytes(messageSizeBytes, 0, 4, cancellationToken); | ||
var readTimeout = _stream.CanTimeout ? TimeSpan.FromMilliseconds(_stream.ReadTimeout) : Timeout.InfiniteTimeSpan; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems weird to be getting the Also, why do we care about There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This code is inhereted/copied from the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree that There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ok. Should I remove checking the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, I think we can ignore this now as we are doing our own timeouts. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As it was discussed offline - will keep it for now. It will be replaced by CSOT timeout on the later stages of implementation. |
||
_stream.ReadBytes(messageSizeBytes, 0, 4, readTimeout, cancellationToken); | ||
var messageSize = BinaryPrimitives.ReadInt32LittleEndian(messageSizeBytes); | ||
EnsureMessageSizeIsValid(messageSize); | ||
var inputBufferChunkSource = new InputBufferChunkSource(BsonChunkPool.Default); | ||
var buffer = ByteBufferFactory.Create(inputBufferChunkSource, messageSize); | ||
buffer.Length = messageSize; | ||
buffer.SetBytes(0, messageSizeBytes, 0, 4); | ||
_stream.ReadBytes(buffer, 4, messageSize - 4, cancellationToken); | ||
_stream.ReadBytes(buffer, 4, messageSize - 4, readTimeout, cancellationToken); | ||
_lastUsedAtUtc = DateTime.UtcNow; | ||
buffer.MakeReadOnly(); | ||
return buffer; | ||
|
@@ -535,7 +536,8 @@ private void SendBuffer(IByteBuffer buffer, CancellationToken cancellationToken) | |
|
||
try | ||
{ | ||
_stream.WriteBytes(buffer, 0, buffer.Length, cancellationToken); | ||
var writeTimeout = _stream.CanTimeout ? TimeSpan.FromMilliseconds(_stream.WriteTimeout) : Timeout.InfiniteTimeSpan; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Similar question here as for |
||
_stream.WriteBytes(buffer, 0, buffer.Length, writeTimeout, cancellationToken); | ||
_lastUsedAtUtc = DateTime.UtcNow; | ||
} | ||
catch (Exception ex) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -138,7 +138,11 @@ private void Connect(Socket socket, EndPoint endPoint, CancellationToken cancell | |
|
||
if (!connectOperation.IsCompleted) | ||
{ | ||
try { socket.Dispose(); } catch { } | ||
try | ||
{ | ||
socket.Dispose(); | ||
socket.EndConnect(connectOperation); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't these calls be reversed? You shouldn't be calling methods on an object after disposal. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've removed EndConnect call. We do have to await on task returned for async code path to observe the exception. I was under impression that same logic is applicable for Begin/End approach, but it is not. |
||
} catch { } | ||
|
||
cancellationToken.ThrowIfCancellationRequested(); | ||
throw new TimeoutException($"Timed out connecting to {endPoint}. Timeout was {_settings.ConnectTimeout}."); | ||
|
@@ -164,7 +168,11 @@ private async Task ConnectAsync(Socket socket, EndPoint endPoint, CancellationTo | |
|
||
if (!connectTask.IsCompleted) | ||
{ | ||
try { socket.Dispose(); } catch { } | ||
try | ||
{ | ||
socket.Dispose(); | ||
await connectTask.ConfigureAwait(false); | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} catch { } | ||
|
||
cancellationToken.ThrowIfCancellationRequested(); | ||
throw new TimeoutException($"Timed out connecting to {endPoint}. Timeout was {_settings.ConnectTimeout}."); | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -36,46 +36,76 @@ public static void EfficientCopyTo(this Stream input, Stream output) | |
} | ||
} | ||
|
||
public static async Task<int> ReadAsync(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
public static int Read(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
{ | ||
var state = 1; // 1 == reading, 2 == done reading, 3 == timedout, 4 == cancelled | ||
|
||
var bytesRead = 0; | ||
using (new Timer(_ => ChangeState(3), null, timeout, Timeout.InfiniteTimeSpan)) | ||
using (cancellationToken.Register(() => ChangeState(4))) | ||
IAsyncResult readOperation; | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
try | ||
{ | ||
try | ||
using var manualResetEvent = new ManualResetEventSlim(); | ||
readOperation = stream.BeginRead(buffer, offset, count, state => | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
bytesRead = await stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); | ||
ChangeState(2); // note: might not actually go to state 2 if already in state 3 or 4 | ||
} | ||
catch when (state == 1) | ||
((ManualResetEventSlim)state.AsyncState).Set(); | ||
}, manualResetEvent); | ||
|
||
try | ||
{ | ||
try { stream.Dispose(); } catch { } | ||
throw; | ||
if (readOperation.IsCompleted || manualResetEvent.Wait(timeout, cancellationToken)) | ||
{ | ||
return stream.EndRead(readOperation); | ||
} | ||
} | ||
catch when (state >= 3) | ||
catch (OperationCanceledException) | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// a timeout or operation cancelled exception will be thrown instead | ||
// Have to suppress OperationCanceledException here, it will be thrown after the stream will be disposed. | ||
} | ||
} | ||
catch (ObjectDisposedException ex) | ||
{ | ||
throw new EndOfStreamException("The connection was interrupted.", ex); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Have to catch There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How would we ever reach this line? Any There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is another code path. We could get There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've re-wrote the code to avoid the confusion. |
||
} | ||
|
||
if (state == 3) { throw new TimeoutException(); } | ||
if (state == 4) { throw new OperationCanceledException(); } | ||
try | ||
{ | ||
stream.Dispose(); | ||
stream.EndRead(readOperation); | ||
} | ||
catch | ||
{ | ||
// ignore any exceptions | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: Capital There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
} | ||
|
||
return bytesRead; | ||
cancellationToken.ThrowIfCancellationRequested(); | ||
throw new TimeoutException(); | ||
} | ||
|
||
public static async Task<int> ReadAsync(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
{ | ||
var timeoutTask = Task.Delay(timeout, cancellationToken); | ||
var readTask = stream.ReadAsync(buffer, offset, count); | ||
|
||
await Task.WhenAny(readTask, timeoutTask).ConfigureAwait(false); | ||
|
||
void ChangeState(int to) | ||
if (!readTask.IsCompleted) | ||
{ | ||
var from = Interlocked.CompareExchange(ref state, to, 1); | ||
if (from == 1 && to >= 3) | ||
try | ||
{ | ||
try { stream.Dispose(); } catch { } // disposing the stream aborts the read attempt | ||
stream.Dispose(); | ||
// should await in the read task to avoid UnobservedTaskException | ||
await readTask.ConfigureAwait(false); | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
catch | ||
{ | ||
// ignore any exceptions | ||
} | ||
|
||
cancellationToken.ThrowIfCancellationRequested(); | ||
throw new TimeoutException(); | ||
} | ||
|
||
return await readTask.ConfigureAwait(false); | ||
} | ||
|
||
public static void ReadBytes(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) | ||
public static void ReadBytes(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
{ | ||
Ensure.IsNotNull(stream, nameof(stream)); | ||
Ensure.IsNotNull(buffer, nameof(buffer)); | ||
|
@@ -84,7 +114,7 @@ public static void ReadBytes(this Stream stream, byte[] buffer, int offset, int | |
|
||
while (count > 0) | ||
{ | ||
var bytesRead = stream.Read(buffer, offset, count); // TODO: honor cancellationToken? | ||
var bytesRead = stream.Read(buffer, offset, count, timeout, cancellationToken); | ||
if (bytesRead == 0) | ||
{ | ||
throw new EndOfStreamException(); | ||
|
@@ -94,7 +124,7 @@ public static void ReadBytes(this Stream stream, byte[] buffer, int offset, int | |
} | ||
} | ||
|
||
public static void ReadBytes(this Stream stream, IByteBuffer buffer, int offset, int count, CancellationToken cancellationToken) | ||
public static void ReadBytes(this Stream stream, IByteBuffer buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
{ | ||
Ensure.IsNotNull(stream, nameof(stream)); | ||
Ensure.IsNotNull(buffer, nameof(buffer)); | ||
|
@@ -105,7 +135,7 @@ public static void ReadBytes(this Stream stream, IByteBuffer buffer, int offset, | |
{ | ||
var backingBytes = buffer.AccessBackingBytes(offset); | ||
var bytesToRead = Math.Min(count, backingBytes.Count); | ||
var bytesRead = stream.Read(backingBytes.Array, backingBytes.Offset, bytesToRead); // TODO: honor cancellationToken? | ||
var bytesRead = stream.Read(backingBytes.Array, backingBytes.Offset, bytesToRead, timeout, cancellationToken); | ||
if (bytesRead == 0) | ||
{ | ||
throw new EndOfStreamException(); | ||
|
@@ -155,44 +185,76 @@ public static async Task ReadBytesAsync(this Stream stream, IByteBuffer buffer, | |
} | ||
} | ||
|
||
|
||
public static async Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
public static void Write(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
{ | ||
var state = 1; // 1 == writing, 2 == done writing, 3 == timedout, 4 == cancelled | ||
|
||
using (new Timer(_ => ChangeState(3), null, timeout, Timeout.InfiniteTimeSpan)) | ||
using (cancellationToken.Register(() => ChangeState(4))) | ||
IAsyncResult writeOperation; | ||
try | ||
{ | ||
try | ||
using var manualResetEvent = new ManualResetEventSlim(); | ||
writeOperation = stream.BeginWrite(buffer, offset, count, state => | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); | ||
ChangeState(2); // note: might not actually go to state 2 if already in state 3 or 4 | ||
} | ||
catch when (state == 1) | ||
((ManualResetEventSlim)state.AsyncState).Set(); | ||
}, manualResetEvent); | ||
|
||
try | ||
{ | ||
try { stream.Dispose(); } catch { } | ||
throw; | ||
if (writeOperation.IsCompleted || manualResetEvent.Wait(timeout, cancellationToken)) | ||
{ | ||
stream.EndWrite(writeOperation); | ||
return; | ||
} | ||
} | ||
catch when (state >= 3) | ||
catch (OperationCanceledException) | ||
{ | ||
// a timeout or operation cancelled exception will be thrown instead | ||
// Have to suppress OperationCanceledException here, it will be thrown after the stream will be disposed. | ||
} | ||
} | ||
catch (ObjectDisposedException ex) | ||
{ | ||
throw new EndOfStreamException("The connection was interrupted.", ex); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So we don't have There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good question. Will double-check. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As per our discussion: async code-path do not require catching ObjectDisposedException. Also we agreed to replace EndOfStreamException with IOException, to match the throwed exception from async code path. |
||
} | ||
|
||
if (state == 3) { throw new TimeoutException(); } | ||
if (state == 4) { throw new OperationCanceledException(); } | ||
try | ||
{ | ||
stream.Dispose(); | ||
stream.EndWrite(writeOperation); | ||
} | ||
catch | ||
{ | ||
// ignore any exceptions | ||
} | ||
|
||
void ChangeState(int to) | ||
cancellationToken.ThrowIfCancellationRequested(); | ||
throw new TimeoutException(); | ||
} | ||
|
||
public static async Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
{ | ||
var timeoutTask = Task.Delay(timeout, cancellationToken); | ||
var writeTask = stream.WriteAsync(buffer, offset, count); | ||
|
||
await Task.WhenAny(writeTask, timeoutTask).ConfigureAwait(false); | ||
|
||
if (!writeTask.IsCompleted) | ||
{ | ||
var from = Interlocked.CompareExchange(ref state, to, 1); | ||
if (from == 1 && to >= 3) | ||
try | ||
{ | ||
stream.Dispose(); | ||
await writeTask.ConfigureAwait(false); | ||
} | ||
catch | ||
{ | ||
try { stream.Dispose(); } catch { } // disposing the stream aborts the write attempt | ||
// ignore any exceptions | ||
} | ||
|
||
cancellationToken.ThrowIfCancellationRequested(); | ||
throw new TimeoutException(); | ||
} | ||
|
||
await writeTask.ConfigureAwait(false); | ||
} | ||
|
||
public static void WriteBytes(this Stream stream, IByteBuffer buffer, int offset, int count, CancellationToken cancellationToken) | ||
public static void WriteBytes(this Stream stream, IByteBuffer buffer, int offset, int count, TimeSpan timeout, CancellationToken cancellationToken) | ||
{ | ||
Ensure.IsNotNull(stream, nameof(stream)); | ||
Ensure.IsNotNull(buffer, nameof(buffer)); | ||
|
@@ -204,7 +266,7 @@ public static void WriteBytes(this Stream stream, IByteBuffer buffer, int offset | |
cancellationToken.ThrowIfCancellationRequested(); | ||
var backingBytes = buffer.AccessBackingBytes(offset); | ||
var bytesToWrite = Math.Min(count, backingBytes.Count); | ||
stream.Write(backingBytes.Array, backingBytes.Offset, bytesToWrite); // TODO: honor cancellationToken? | ||
stream.Write(backingBytes.Array, backingBytes.Offset, bytesToWrite, timeout, cancellationToken); // TODO: honor cancellationToken? | ||
BorisDog marked this conversation as resolved.
Show resolved
Hide resolved
|
||
offset += bytesToWrite; | ||
count -= bytesToWrite; | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Curious why this change is needed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because this code uses helper method that I've adjusted with new parameter, so I should pass something from here too.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will
stream.ReadTimeout
still be respected byBeginRead
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As far as I understood Compress/Decompress works only with in-memory kind of streams. Not sure if timeout makes sense in such case.