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

Invoke-WebRequest and Invoke-RestMethod: Rename TimeoutSec to ConnectionTimeoutSeconds (with alias) and add OperationTimeoutSeconds #19558

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Set FullyQualifiedErrorId as per feedback from review
  • Loading branch information
stevenebutler committed Jun 17, 2023
commit a8acd173604183df92b2257f7826f4fe9af902ea
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,11 @@ protected override void ProcessRecord()
WriteError(er);
}
}
catch (TimeoutException ex)
{
ErrorRecord er = new(ex, "OperationTimeoutReached", ErrorCategory.OperationTimeout, null);
ThrowTerminatingError(er);
}
catch (HttpRequestException ex)
{
ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request);
Expand Down Expand Up @@ -1284,8 +1289,24 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM
Uri currentUri = currentRequest.RequestUri;

_cancelToken = new CancellationTokenSource();
response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult();
try
{
response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult();
}
catch (TaskCanceledException ex)
{
if (ex.InnerException is TimeoutException)
{
// HTTP Request timed out
ErrorRecord er = new(ex, "ConnectionTimeoutReached", ErrorCategory.OperationTimeout, null);
ThrowTerminatingError(er);
}
else
{
throw;
}

}
if (handleRedirect
&& _maximumRedirection is not 0
&& IsRedirectCode(response.StatusCode)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,22 @@ internal static async Task<int> ReadAsync(this Stream stream, Memory<byte> buffe
}

using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(readTimeout);
return await stream.ReadAsync(buffer, cts.Token).ConfigureAwait(false);
try
{
cts.CancelAfter(readTimeout);
return await stream.ReadAsync(buffer, cts.Token).ConfigureAwait(false);
}
catch (TaskCanceledException ex)
{
if (cts.IsCancellationRequested)
{
throw new TimeoutException($"The request was canceled due to the configured OperationTimeout of {readTimeout.TotalSeconds} seconds elapsing", ex);
}
else
{
throw;
}
}
}

internal static async Task CopyToAsync(this Stream source, Stream destination, TimeSpan perReadTimeout, CancellationToken cancellationToken)
Expand Down Expand Up @@ -304,6 +318,17 @@ internal static async Task CopyToAsync(this Stream source, Stream destination, T
await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false);
}
}
catch (TaskCanceledException ex)
{
if (cts.IsCancellationRequested)
{
throw new TimeoutException($"The request was canceled due to the configured OperationTimeout of {perReadTimeout.TotalSeconds} seconds elapsing", ex);
}
else
{
throw;
}
}
finally
{
cts.Dispose();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -613,15 +613,15 @@ Describe "Invoke-WebRequest tests" -Tags "Feature", "RequireAdminOnWindows" {
$command = "Invoke-WebRequest -Uri '$uri' -ConnectionTimeoutSeconds 2"

$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should -Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
$result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}

It "Invoke-WebRequest validate TimeoutSec alias" {
$uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5'
$command = "Invoke-WebRequest -Uri '$uri' -TimeoutSec 2"

$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should -Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
$result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
}

It "Validate Invoke-WebRequest error with -Proxy and -NoProxy option" {
Expand Down Expand Up @@ -2663,15 +2663,15 @@ Describe "Invoke-RestMethod tests" -Tags "Feature", "RequireAdminOnWindows" {
$command = "Invoke-RestMethod -Uri '$uri' -ConnectionTimeoutSeconds 2"

$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should -Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand"
$result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeRestMethodCommand"
}

It "Invoke-RestMethod validate TimeoutSec alias" {
$uri = Get-WebListenerUrl -Test 'Delay' -TestValue '5'
$command = "Invoke-RestMethod -Uri '$uri' -TimeoutSec 2"

$result = ExecuteWebCommand -command $command
$result.Error.FullyQualifiedErrorId | Should -Be "System.Threading.Tasks.TaskCanceledException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand"
$result.Error.FullyQualifiedErrorId | Should -Be "ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeRestMethodCommand"
}

It "Validate Invoke-RestMethod error with -Proxy and -NoProxy option" {
Expand Down Expand Up @@ -4409,7 +4409,7 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support Cancellation through C
RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck'
}

It 'Invoke-WebRequest: HTTPS with Defalte compression CTRL-C Cancels request after request headers' {
It 'Invoke-WebRequest: HTTPS with Deflate compression CTRL-C Cancels request after request headers' {
$uri = Get-WebListenerUrl -Https -Test StallDeflate -TestValue '30/application%2fjson'
RunWithCancellation -Uri $uri -Arguments '-SkipCertificateCheck'
}
Expand Down Expand Up @@ -4494,6 +4494,8 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support OperationTimeoutSecond
$result = ExecuteWebCommand -command $invoke
if ($WillTimeout) {
$result.Error | Should -Not -BeNullOrEmpty
$fqErrorClass = if ($Command -eq 'Invoke-WebRequest') { 'InvokeWebRequestCommand'} else { 'InvokeRestMethodCommand'}
$result.Error.FullyQualifiedErrorId | Should -Be "OperationTimeoutReached,Microsoft.PowerShell.Commands.$fqErrorClass"
$result.Output | Should -BeNullOrEmpty
} else {
$result.Error | Should -BeNullOrEmpty
Expand Down