Skip to content

Commit

Permalink
#702 move CancellationToken to last arg
Browse files Browse the repository at this point in the history
  • Loading branch information
tmenier committed Jun 10, 2022
1 parent e7188f0 commit 04344cd
Show file tree
Hide file tree
Showing 10 changed files with 364 additions and 363 deletions.
6 changes: 3 additions & 3 deletions Test/Flurl.Test/Http/RealHttpTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ public void can_set_timeout() {
public void can_cancel_request() {
var cts = new CancellationTokenSource();
var ex = Assert.ThrowsAsync<FlurlHttpException>(async () => {
var task = "https://httpbin.org/delay/5".GetAsync(cts.Token);
var task = "https://httpbin.org/delay/5".GetAsync(cancellationToken: cts.Token);
cts.Cancel();
await task;
});
Expand All @@ -215,7 +215,7 @@ public void can_set_timeout_and_cancellation_token() {
var ex = Assert.ThrowsAsync<FlurlHttpException>(async () => {
var task = "https://httpbin.org/delay/5"
.WithTimeout(TimeSpan.FromMilliseconds(50))
.GetAsync(cts.Token);
.GetAsync(cancellationToken: cts.Token);
cts.Cancel();
await task;
});
Expand All @@ -227,7 +227,7 @@ public void can_set_timeout_and_cancellation_token() {
ex = Assert.ThrowsAsync<FlurlHttpTimeoutException>(async () => {
await "https://httpbin.org/delay/5"
.WithTimeout(TimeSpan.FromMilliseconds(50))
.GetAsync(cts.Token);
.GetAsync(cancellationToken: cts.Token);
});
Assert.That(ex.InnerException is OperationCanceledException);
Assert.IsFalse(cts.Token.IsCancellationRequested);
Expand Down
16 changes: 10 additions & 6 deletions src/Flurl.CodeGen/HttpExtensionMethod.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System;

namespace Flurl.CodeGen
{
public class HttpExtensionMethod : ExtensionMethod
Expand All @@ -11,19 +13,21 @@ public HttpExtensionMethod(string verb, bool isGeneric, string reqBodyType, stri
if (verb == null)
AddArg("verb", "HttpMethod", "The HTTP verb used to make the request.");

if (HasRequestBody) {
if (HasRequestBody) {
if (reqBodyType == "Json")
AddArg("data", "object", "An object representing the request body, which will be serialized to JSON.");
AddArg("body", "object", "An object representing the request body, which will be serialized to JSON.");
else if (reqBodyType == "UrlEncoded")
AddArg("body", "object", "An object representing the request body, which will be serialized to a URL-encoded string.");
else if (reqBodyType == "String")
AddArg("data", "string", "Contents of the request body.");
AddArg("body", "string", "The request body.");
else if (reqBodyType == null)
AddArg("content", "HttpContent", "Contents of the request body.", "null");
AddArg("content", "HttpContent", "The request body content.", "null");
else
AddArg("data", "object", "Contents of the request body.");
throw new Exception("how did we get here?");
}

AddArg("cancellationToken", "CancellationToken", "The token to monitor for cancellation requests.", "default(CancellationToken)");
AddArg("completionOption", "HttpCompletionOption", "The HttpCompletionOption used in the request. Optional.", "HttpCompletionOption.ResponseContentRead");
AddArg("cancellationToken", "CancellationToken", "The token to monitor for cancellation requests.", "default");

Returns($"Task<{TaskArg}>", $"A Task whose result is {ReturnTypeDescription}.");
}
Expand Down
4 changes: 2 additions & 2 deletions src/Flurl.CodeGen/Metadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,13 @@ public static IEnumerable<ExtensionMethod> GetRequestReturningExtensions(MethodA
.AddArg("localFolderPath", "string", "Path of local folder where file is to be downloaded.")
.AddArg("localFileName", "string", "Name of local file. If not specified, the source filename (last segment of the URL) is used.", "null")
.AddArg("bufferSize", "int", "Buffer size in bytes. Default is 4096.", "4096")
.AddArg("cancellationToken", "CancellationToken", "The token to monitor for cancellation requests.", "default(CancellationToken)");
.AddArg("cancellationToken", "CancellationToken", "The token to monitor for cancellation requests.", "default");

yield return new ExtensionMethod("PostMultipartAsync", "Creates a FlurlRequest and sends an asynchronous multipart/form-data POST request.")
.Returns("Task<IFlurlResponse>", "A Task whose result is the received IFlurlResponse.")
.Extends(extendedArg)
.AddArg("buildContent", "Action<CapturedMultipartContent>", "A delegate for building the content parts.")
.AddArg("cancellationToken", "CancellationToken", "The token to monitor for cancellation requests.", "default(CancellationToken)");
.AddArg("cancellationToken", "CancellationToken", "The token to monitor for cancellation requests.", "default");
}

/// <summary>
Expand Down
10 changes: 4 additions & 6 deletions src/Flurl.CodeGen/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,14 @@ private static void WriteHttpExtensionMethods(CodeWriter writer) {
xm.HttpVerb == "Patch" ? "new HttpMethod(\"PATCH\")" : // there's no HttpMethod.Patch
"HttpMethod." + xm.HttpVerb);

if (xm.HasRequestBody)
args.Add("content: content");

args.Add("cancellationToken: cancellationToken");
args.Add("completionOption: completionOption");
args.Add(xm.HasRequestBody ? "content" : "null");
args.Add("completionOption");
args.Add("cancellationToken");

if (xm.RequestBodyType != null) {
writer.WriteLine("var content = new Captured@0Content(@1);",
xm.RequestBodyType,
xm.RequestBodyType == "String" ? "data" : $"request.Settings.{xm.RequestBodyType}Serializer.Serialize(data)");
xm.RequestBodyType == "String" ? "body" : $"request.Settings.{xm.RequestBodyType}Serializer.Serialize(body)");
}

var receive = (xm.ResponseBodyType != null) ? $".Receive{xm.ResponseBodyType}{genericArg}()" : "";
Expand Down
2 changes: 1 addition & 1 deletion src/Flurl.Http/Configuration/FlurlHttpSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ internal T Get<T>([CallerMemberName]string propName = null) {
testVals?.ContainsKey(propName) == true ? (T)testVals[propName] :
_vals.ContainsKey(propName) ? (T)_vals[propName] :
Defaults != null ? (T)Defaults.Get<T>(propName) :
default(T);
default;
}

/// <summary>
Expand Down
7 changes: 3 additions & 4 deletions src/Flurl.Http/DownloadExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ public static class DownloadExtensions
/// <param name="bufferSize">Buffer size in bytes. Default is 4096.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A Task whose result is the local path of the downloaded file.</returns>
public static async Task<string> DownloadFileAsync(this IFlurlRequest request, string localFolderPath, string localFileName = null, int bufferSize = 4096, CancellationToken cancellationToken = default(CancellationToken)) {
using (var resp = await request.SendAsync(HttpMethod.Get, cancellationToken: cancellationToken, completionOption: HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)) {
localFileName =
localFileName ??
public static async Task<string> DownloadFileAsync(this IFlurlRequest request, string localFolderPath, string localFileName = null, int bufferSize = 4096, CancellationToken cancellationToken = default) {
using (var resp = await request.SendAsync(HttpMethod.Get, null, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false)) {
localFileName ??=
GetFileNameFromHeaders(resp.ResponseMessage) ??
GetFileNameFromPath(request);

Expand Down
12 changes: 6 additions & 6 deletions src/Flurl.Http/FlurlRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public interface IFlurlRequest : IHttpSettingsContainer
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <param name="completionOption">The HttpCompletionOption used in the request. Optional.</param>
/// <returns>A Task whose result is the received IFlurlResponse.</returns>
Task<IFlurlResponse> SendAsync(HttpMethod verb, HttpContent content = null, CancellationToken cancellationToken = default(CancellationToken), HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead);
Task<IFlurlResponse> SendAsync(HttpMethod verb, HttpContent content = null, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, CancellationToken cancellationToken = default);
}

/// <inheritdoc />
Expand Down Expand Up @@ -157,7 +157,7 @@ where c.ShouldSendTo(this.Url, out _)
}

/// <inheritdoc />
public async Task<IFlurlResponse> SendAsync(HttpMethod verb, HttpContent content = null, CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) {
public async Task<IFlurlResponse> SendAsync(HttpMethod verb, HttpContent content = null, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, CancellationToken cancellationToken = default) {
_client = Client; // "freeze" the client at this point to avoid excessive calls to FlurlClientFactory.Get (#374)
Verb = verb;

Expand Down Expand Up @@ -186,7 +186,7 @@ public async Task<IFlurlResponse> SendAsync(HttpMethod verb, HttpContent content
call.Response = new FlurlResponse(call.HttpResponseMessage, CookieJar);

if (call.Succeeded) {
var redirResponse = await ProcessRedirectAsync(call, cancellationToken, completionOption).ConfigureAwait(false);
var redirResponse = await ProcessRedirectAsync(call, completionOption, cancellationToken).ConfigureAwait(false);
return redirResponse ?? call.Response;
}
else
Expand Down Expand Up @@ -231,7 +231,7 @@ private CancellationToken GetCancellationTokenWithTimeout(CancellationToken orig
}
}

private async Task<IFlurlResponse> ProcessRedirectAsync(FlurlCall call, CancellationToken cancellationToken, HttpCompletionOption completionOption) {
private async Task<IFlurlResponse> ProcessRedirectAsync(FlurlCall call, HttpCompletionOption completionOption, CancellationToken cancellationToken) {
if (Settings.Redirects.Enabled)
call.Redirect = GetRedirect(call);

Expand Down Expand Up @@ -267,8 +267,8 @@ private async Task<IFlurlResponse> ProcessRedirectAsync(FlurlCall call, Cancella
return await redir.SendAsync(
changeToGet ? HttpMethod.Get : call.HttpRequestMessage.Method,
changeToGet ? null : call.HttpRequestMessage.Content,
ct,
completionOption).ConfigureAwait(false);
completionOption,
ct).ConfigureAwait(false);
}
finally {
cts?.Dispose();
Expand Down
Loading

0 comments on commit 04344cd

Please sign in to comment.