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

Version 1.0.3.0 #5

Merged
merged 14 commits into from
Nov 8, 2024
Merged
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
7 changes: 6 additions & 1 deletion Changelog.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Changelog

## Version 1.0.2
## Version 1.0.3.0

- Added `-t, --timeout` parameter to specify the timeout in milliseconds (default: -1 - infinity)
- Fixed handling of timeouts as HttpClient hides the exception under `TaskCanceledException` leading to same output and handling as manual user cancellation, which was incorrect

## Version 1.0.2.0

- Added `-o, --output` parameter to specify the output folder (default: "results")
- Updated automations to add ubuntu 20.04 support to address issues with glibc2.31
Expand Down
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ RequestFile:
- If you don't have one use the "get-sample" command
Options:
-n, --number : number of total requests (default: 1)
-t, --timeout : timeout in milliseconds (default: -1 - infinity)
-m, --mode : execution mode (default: parallel)
* sequential = execute requests sequentially
* parallel = execute requests using maximum resources
Expand Down
10 changes: 10 additions & 0 deletions src/Pulse/Configuration/Parameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public record ParametersBase {
/// </summary>
public const int DefaultBatchSize = 1;

/// <summary>
/// Default timeout in milliseconds (infinity)
/// </summary>
public const int DefaultTimeoutInMs = -1;

/// <summary>
/// Default execution mode
/// </summary>
Expand All @@ -26,6 +31,11 @@ public record ParametersBase {
/// </summary>
public int Requests { get; set; } = DefaultNumberOfRequests;

/// <summary>
/// Sets the timeout in milliseconds
/// </summary>
public int TimeoutInMs { get; set; } = DefaultTimeoutInMs;

/// <summary>
/// Sets the execution mode (default = <see cref="DefaultExecutionMode"/>)
/// </summary>
Expand Down
14 changes: 14 additions & 0 deletions src/Pulse/Configuration/StrippedException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ private StrippedException(Exception exception) {
Type = exception.GetType().Name;
Message = exception.Message;
StackTrace = exception.StackTrace ?? "";
IsDefault = false;
}

/// <summary>
/// Creates a stripped exception from a type, message and stack trace
/// </summary>
/// <param name="type"></param>
/// <param name="message"></param>
/// <param name="stackTrace"></param>
public StrippedException(string type, string message, string stackTrace) {
Type = type;
Message = message;
StackTrace = stackTrace;
IsDefault = false;
}

[JsonConstructor]
Expand Down
6 changes: 3 additions & 3 deletions src/Pulse/Core/Pulse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static Task RunAsync(Parameters parameters, RequestDetails requestDetails
/// <param name="parameters"></param>
/// <param name="requestDetails"></param>
internal static async Task RunSequential(Parameters parameters, RequestDetails requestDetails) {
using var httpClient = PulseHttpClientFactory.Create(requestDetails.Proxy);
using var httpClient = PulseHttpClientFactory.Create(requestDetails.Proxy, parameters.TimeoutInMs);

var monitor = new PulseMonitor {
RequestCount = parameters.Requests,
Expand Down Expand Up @@ -60,7 +60,7 @@ internal static async Task RunSequential(Parameters parameters, RequestDetails r
/// <param name="parameters"></param>
/// <param name="requestDetails"></param>
internal static async Task RunBounded(Parameters parameters, RequestDetails requestDetails) {
using var httpClient = PulseHttpClientFactory.Create(requestDetails.Proxy);
using var httpClient = PulseHttpClientFactory.Create(requestDetails.Proxy, parameters.TimeoutInMs);

var cancellationToken = parameters.CancellationToken;

Expand Down Expand Up @@ -110,7 +110,7 @@ internal static async Task RunBounded(Parameters parameters, RequestDetails requ
/// <param name="parameters"></param>
/// <param name="requestDetails"></param>
internal static async Task RunUnbounded(Parameters parameters, RequestDetails requestDetails) {
using var httpClient = PulseHttpClientFactory.Create(requestDetails.Proxy);
using var httpClient = PulseHttpClientFactory.Create(requestDetails.Proxy, parameters.TimeoutInMs);

var cancellationToken = parameters.CancellationToken;

Expand Down
4 changes: 2 additions & 2 deletions src/Pulse/Core/PulseHttpClientFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public static class PulseHttpClientFactory {
/// </summary>
/// <param name="proxyDetails"></param>
/// <returns>An HttpClient</returns>
public static HttpClient Create(Proxy proxyDetails) {
public static HttpClient Create(Proxy proxyDetails, int TimeoutInMs) {
SocketsHttpHandler handler = CreateHandler(proxyDetails);

return new HttpClient(handler) {
Timeout = TimeSpan.FromMinutes(10)
Timeout = TimeSpan.FromMilliseconds(TimeoutInMs)
};
}

Expand Down
12 changes: 8 additions & 4 deletions src/Pulse/Core/PulseMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public async Task SendAsync(int requestId) {
internal static async Task<Response> SendRequest(int id, Request requestRecipe, HttpClient httpClient, bool saveContent, CancellationToken cancellationToken = default) {
HttpStatusCode statusCode = 0;
string content = "";
Exception? exception = null;
StrippedException exception = StrippedException.Default;
var headers = Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>();
int threadId = 0;
using var message = requestRecipe.CreateMessage();
Expand All @@ -103,9 +103,13 @@ internal static async Task<Response> SendRequest(int id, Request requestRecipe,
content = await response.Content.ReadAsStringAsync(cancellationToken);
}
} catch (Exception e) when (e is TaskCanceledException or OperationCanceledException) {
throw;
if (cancellationToken.IsCancellationRequested) {
throw;
}
var elapsed = Stopwatch.GetElapsedTime(start);
exception = new StrippedException(nameof(TimeoutException), $"Request {id} timeout after {elapsed.TotalMilliseconds} ms", "");
} catch (Exception e) {
exception = e;
exception = StrippedException.FromException(e);
} finally {
message?.Dispose();
}
Expand All @@ -116,7 +120,7 @@ internal static async Task<Response> SendRequest(int id, Request requestRecipe,
Headers = headers,
Content = content,
Duration = duration,
Exception = StrippedException.FromException(exception),
Exception = exception,
ExecutingThreadId = threadId
};
}
Expand Down
14 changes: 11 additions & 3 deletions src/Pulse/Core/SendCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ path to .json request details file
- If you don't have one use the "get-sample" command
Options:
-n, --number : number of total requests (default: 1)
-t, --timeout : timeout in milliseconds (default: -1 - infinity)
-m, --mode : execution mode (default: parallel)
* sequential = execute requests sequentially
* parallel = execute requests using maximum resources
Expand All @@ -53,6 +54,7 @@ path to .json request details file
internal static ParametersBase ParseParametersArgs(Arguments args) {
args.TryGetValue(["n", "number"], ParametersBase.DefaultNumberOfRequests, out int requests);
requests = Math.Max(requests, 1);
args.TryGetValue(["t", "timeout"], ParametersBase.DefaultTimeoutInMs, out int timeoutInMs);
bool batchSizeModified = false;
args.TryGetEnum(["m", "mode"], ParametersBase.DefaultExecutionMode, true, out ExecutionMode mode);
if (args.TryGetValue(["b", "batch"], ParametersBase.DefaultBatchSize, out int batchSize)) {
Expand All @@ -67,6 +69,7 @@ internal static ParametersBase ParseParametersArgs(Arguments args) {
bool verbose = args.HasFlag("v") || args.HasFlag("verbose");
return new ParametersBase {
Requests = requests,
TimeoutInMs = timeoutInMs,
ExecutionMode = mode,
BatchSize = batchSize,
BatchSizeModified = batchSizeModified,
Expand Down Expand Up @@ -169,11 +172,15 @@ public override async ValueTask<int> ExecuteAsync(Arguments args) {
if (result.IsFail) {
return;
}
var version = result.Message;
if (string.Compare(Program.VERSION, version) < 0) {
if (!Version.TryParse(result.Message, out Version? remoteVersion)) {
WriteLineError("Failed to parse remote version.");
return;
}
var currentVersion = Version.Parse(Program.VERSION);
if (currentVersion < remoteVersion) {
WriteLine("A new version of Pulse is available!" * Color.Yellow);
WriteLine(["Your version: ", Program.VERSION * Color.Yellow]);
WriteLine(["Latest version: ", version * Color.Green]);
WriteLine(["Latest version: ", remoteVersion.ToString() * Color.Green]);
NewLine();
WriteLine("Download from https://github.com/dusrdev/Pulse/releases/latest");
} else {
Expand Down Expand Up @@ -205,6 +212,7 @@ internal static void PrintConfiguration(Parameters parameters, RequestDetails re
// Options
WriteLine("Options:" * headerColor);
WriteLine([" Request Count: " * property, $"{parameters.Requests}" * value]);
WriteLine([" Timeout: " * property, $"{parameters.TimeoutInMs}" * value]);
WriteLine([" Execution Mode: " * property, $"{parameters.ExecutionMode}" * value]);
#pragma warning disable IDE0002
if (parameters.BatchSize is not Parameters.DefaultBatchSize) {
Expand Down
2 changes: 1 addition & 1 deletion src/Pulse/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using PrettyConsole;

internal class Program {
internal const string VERSION = "1.0.2.0";
internal const string VERSION = "1.0.3.0";

private static async Task<int> Main(string[] args) {
using CancellationTokenSource globalCTS = new();
Expand Down
2 changes: 1 addition & 1 deletion src/Pulse/Pulse.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<PublishAot>true</PublishAot>
<IsAotCompatible>true</IsAotCompatible>
<AotCompatible>true</AotCompatible>
<Version>1.0.2.0</Version>
<Version>1.0.3.0</Version>
<StripSymbols>true</StripSymbols>
<RepositoryUrl>https://github.com/dusrdev/Pulse</RepositoryUrl>
<RepositoryType>git</RepositoryType>
Expand Down
16 changes: 15 additions & 1 deletion tests/Pulse.Tests.Unit/HttpClientFactoryTests.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,31 @@
using System.Net;

using Pulse.Configuration;

using Pulse.Core;

namespace Pulse.Tests.Unit;

public class HttpClientFactoryTests {
[Fact]
public void HttpClientFactory_DefaultTimeout_IsInfinite() {
// Arrange
var proxy = new Proxy();

// Act
using var httpClient = PulseHttpClientFactory.Create(proxy, Parameters.DefaultTimeoutInMs);

// Assert
httpClient.Timeout.Should().Be(Timeout.InfiniteTimeSpan, "because the default timeout is infinite");
}

[Fact]
public void HttpClientFactory_WithoutProxy_ReturnsHttpClient() {
// Arrange
var proxy = new Proxy();

// Act
using var httpClient = PulseHttpClientFactory.Create(proxy);
using var httpClient = PulseHttpClientFactory.Create(proxy, Parameters.DefaultTimeoutInMs);

// Assert
httpClient.Should().NotBeNull("because a HttpClient is returned");
Expand Down
23 changes: 23 additions & 0 deletions tests/Pulse.Tests.Unit/PulseMonitorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Pulse.Core;

namespace Pulse.Tests.Unit;

public class PulseMonitorTests {
[Fact]
public async Task SendAsync_ReturnsTimeoutException_OnTimeout() {
// Arrange
var requestDetails = new RequestDetails() {
Proxy = new Proxy(),
Request = new Request() {
Url = "https://google.com",
Method = HttpMethod.Get
}
};

using var httpClient = PulseHttpClientFactory.Create(requestDetails.Proxy, 50);

// Act + Assert
var result = await PulseMonitor.SendRequest(1, requestDetails.Request, httpClient, false, CancellationToken.None);
result.Exception.Type.Should().Be(nameof(TimeoutException));
}
}
16 changes: 16 additions & 0 deletions tests/Pulse.Tests.Unit/SencCommandParsingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ public void Arguments_Flag_NoOp() {
@params.NoOp.Should().BeTrue("because the flag is present");
}

[Theory]
[InlineData("Pulse -v", -1)] // default
[InlineData("Pulse -v -t -1", -1)] // set but default
[InlineData("Pulse --verbose -t 30000", 30000)] // custom
[InlineData("Pulse --verbose --timeout 30000", 30000)] // custom
public void Arguments_Timeout(string arguments, int expected) {
// Arrange
var args = Parser.ParseArguments(arguments)!;

// Act
var @params = SendCommand.ParseParametersArgs(args);

// Assert
@params.TimeoutInMs.Should().Be(expected, "because parsed or default");
}

[Theory]
[InlineData("Pulse -v")]
[InlineData("Pulse --verbose")]
Expand Down