Skip to content
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
125 changes: 125 additions & 0 deletions src/RestSharp/Extensions/AsyncHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Copyright © 2009-2021 John Sheehan, Andrew Young, Alexey Zimarev and RestSharp community
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Adapted from Rebus

using System.Collections.Concurrent;
using System.Runtime.ExceptionServices;

namespace RestSharp.Extensions {
public static class AsyncHelpers {
/// <summary>
/// Executes a task synchronously on the calling thread by installing a temporary synchronization context that queues continuations
/// </summary>
/// <param name="task">Callback for asynchronous task to run</param>
public static void RunSync(Func<Task> task) {
var currentContext = SynchronizationContext.Current;
var customContext = new CustomSynchronizationContext(task);

try {
SynchronizationContext.SetSynchronizationContext(customContext);
customContext.Run();
}
finally {
SynchronizationContext.SetSynchronizationContext(currentContext);
}
}

/// <summary>
/// Executes a task synchronously on the calling thread by installing a temporary synchronization context that queues continuations
/// </summary>
/// <param name="task">Callback for asynchronous task to run</param>
/// <typeparam name="T">Return type for the task</typeparam>
/// <returns>Return value from the task</returns>
public static T RunSync<T>(Func<Task<T>> task) {
T result = default!;
RunSync(async () => { result = await task(); });
return result;
}

/// <summary>
/// Synchronization context that can be "pumped" in order to have it execute continuations posted back to it
/// </summary>
class CustomSynchronizationContext : SynchronizationContext {
readonly ConcurrentQueue<Tuple<SendOrPostCallback, object?>> _items = new();
readonly AutoResetEvent _workItemsWaiting = new(false);
readonly Func<Task> _task;
ExceptionDispatchInfo? _caughtException;
bool _done;

/// <summary>
/// Constructor for the custom context
/// </summary>
/// <param name="task">Task to execute</param>
public CustomSynchronizationContext(Func<Task> task) =>
_task = task ?? throw new ArgumentNullException(nameof(task), "Please remember to pass a Task to be executed");

/// <summary>
/// When overridden in a derived class, dispatches an asynchronous message to a synchronization context.
/// </summary>
/// <param name="function">Callback function</param>
/// <param name="state">Callback state</param>
public override void Post(SendOrPostCallback function, object? state) {
_items.Enqueue(Tuple.Create(function, state));
_workItemsWaiting.Set();
}

/// <summary>
/// Enqueues the function to be executed and executes all resulting continuations until it is completely done
/// </summary>
public void Run() {
async void PostCallback(object? _) {
try {
await _task().ConfigureAwait(false);
}
catch (Exception exception) {
_caughtException = ExceptionDispatchInfo.Capture(exception);
throw;
}
finally {
Post(_ => _done = true, null);
}
}

Post(PostCallback, null);

while (!_done) {
if (_items.TryDequeue(out var task)) {
task.Item1(task.Item2);
if (_caughtException == null) {
continue;
}
_caughtException.Throw();
}
else {
_workItemsWaiting.WaitOne();
}
}
}

/// <summary>
/// When overridden in a derived class, dispatches a synchronous message to a synchronization context.
/// </summary>
/// <param name="function">Callback function</param>
/// <param name="state">Callback state</param>
public override void Send(SendOrPostCallback function, object? state) => throw new NotSupportedException("Cannot send to same thread");

/// <summary>
/// When overridden in a derived class, creates a copy of the synchronization context. Not needed, so just return ourselves.
/// </summary>
/// <returns>Copy of the context</returns>
public override SynchronizationContext CreateCopy() => this;
}
}
}
16 changes: 16 additions & 0 deletions src/RestSharp/RestClient.Async.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using RestSharp.Extensions;

namespace RestSharp;

public partial class RestClient {
/// <summary>
/// Executes the request synchronously, authenticating if needed
/// </summary>
/// <param name="request">Request to be executed</param>
public RestResponse Execute(RestRequest request) => AsyncHelpers.RunSync(() => ExecuteAsync(request));
Copy link
Member

Choose a reason for hiding this comment

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

Do we need it here, or can it be an extension?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Seems simple enough to put it there, but it could be moved to RestClientExtensions I suppose? What would you prefer?

Copy link
Member

Choose a reason for hiding this comment

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

The question is if it should be a part of the potentially returned IRestClient interface. Do you think it makes sense to keep non-async methods as the core functionality?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, I think they should be part of the core functionality and if there was an IRestClient interface, it should include the non-async functions as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

There could be two interfaces, one for sync and one for non to keep it clean, but IRestClient should inherit both as many people will use both sync and async in their code.


/// <summary>
/// Executes the request asynchronously, authenticating if needed
/// </summary>
Expand Down Expand Up @@ -85,6 +93,14 @@ async Task<InternalResponse> ExecuteInternal(RestRequest request, CancellationTo

record InternalResponse(HttpResponseMessage? ResponseMessage, Uri Url, Exception? Exception, CancellationToken TimeoutToken);

/// <summary>
/// A specialized method to download files as streams.
/// </summary>
/// <param name="request">Pre-configured request instance.</param>
/// <returns>The downloaded stream.</returns>
[PublicAPI]
public Stream? DownloadStream(RestRequest request) => AsyncHelpers.RunSync(() => DownloadStreamAsync(request));

/// <summary>
/// A specialized method to download files as streams.
/// </summary>
Expand Down
101 changes: 101 additions & 0 deletions src/RestSharp/RestClientExtensions.Json.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@
namespace RestSharp;

public static partial class RestClientExtensions {
/// <summary>
/// Calls the URL specified in the <code>resource</code> parameter, expecting a JSON response back. Deserializes and returns the response.
/// </summary>
/// <param name="client">RestClient instance</param>
/// <param name="resource">Resource URL</param>
/// <typeparam name="TResponse">Response object type</typeparam>
/// <returns>Deserialized response object</returns>
public static TResponse? GetJson<TResponse>(
this RestClient client,
string resource)
=> AsyncHelpers.RunSync(() => client.GetJsonAsync<TResponse>(resource));

/// <summary>
/// Calls the URL specified in the <code>resource</code> parameter, expecting a JSON response back. Deserializes and returns the response.
/// </summary>
Expand All @@ -32,6 +44,29 @@ public static partial class RestClientExtensions {
return client.GetAsync<TResponse>(request, cancellationToken);
}

/// <summary>
/// Calls the URL specified in the <code>resource</code> parameter, expecting a JSON response back. Deserializes and returns the response.
/// </summary>
/// <param name="client">RestClient instance</param>
/// <param name="resource">Resource URL</param>
/// <param name="parameters">Parameters to pass to the request</param>
/// <typeparam name="TResponse">Response object type</typeparam>
/// <returns>Deserialized response object</returns>
public static TResponse? GetJson<TResponse>(
this RestClient client,
string resource,
object parameters)
=> AsyncHelpers.RunSync(() => client.GetJsonAsync<TResponse>(resource, parameters));

/// <summary>
/// Calls the URL specified in the <code>resource</code> parameter, expecting a JSON response back. Deserializes and returns the response.
/// </summary>
/// <param name="client">RestClient instance</param>
/// <param name="resource">Resource URL</param>
/// <param name="parameters">Parameters to pass to the request</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <typeparam name="TResponse">Response object type</typeparam>
/// <returns>Deserialized response object</returns>
public static Task<TResponse?> GetJsonAsync<TResponse>(
this RestClient client,
string resource,
Expand All @@ -49,6 +84,23 @@ public static partial class RestClientExtensions {
return client.GetAsync<TResponse>(request, cancellationToken);
}

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter.
/// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it.
/// </summary>
/// <param name="client">RestClient instance</param>
/// <param name="resource">Resource URL</param>
/// <param name="request">Request object, must be serializable to JSON</param>
/// <typeparam name="TRequest">Request object type</typeparam>
/// <typeparam name="TResponse">Response object type</typeparam>
/// <returns>Deserialized response object</returns>
public static TResponse? PostJson<TRequest, TResponse>(
this RestClient client,
string resource,
TRequest request
) where TRequest : class
=> AsyncHelpers.RunSync(() => client.PostJsonAsync<TRequest, TResponse>(resource, request));

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter.
/// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it.
Expand All @@ -70,6 +122,22 @@ public static partial class RestClientExtensions {
return client.PostAsync<TResponse>(restRequest, cancellationToken);
}

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter.
/// Expects no response back, just the status code.
/// </summary>
/// <param name="client">RestClient instance</param>
/// <param name="resource">Resource URL</param>
/// <param name="request">Request object, must be serializable to JSON</param>
/// <typeparam name="TRequest">Request object type</typeparam>
/// <returns>Response status code</returns>
public static HttpStatusCode PostJson<TRequest>(
this RestClient client,
string resource,
TRequest request
) where TRequest : class
=> AsyncHelpers.RunSync(() => client.PostJsonAsync(resource, request));

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a POST call to the resource specified in the <code>resource</code> parameter.
/// Expects no response back, just the status code.
Expand All @@ -91,6 +159,23 @@ public static async Task<HttpStatusCode> PostJsonAsync<TRequest>(
return response.StatusCode;
}

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter.
/// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it.
/// </summary>
/// <param name="client">RestClient instance</param>
/// <param name="resource">Resource URL</param>
/// <param name="request">Request object, must be serializable to JSON</param>
/// <typeparam name="TRequest">Request object type</typeparam>
/// <typeparam name="TResponse">Response object type</typeparam>
/// <returns>Deserialized response object</returns>
public static TResponse? PutJson<TRequest, TResponse>(
this RestClient client,
string resource,
TRequest request
) where TRequest : class
=> AsyncHelpers.RunSync(() => client.PutJsonAsync<TRequest, TResponse>(resource, request));

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter.
/// Expects a JSON response back, deserializes it to <code>TResponse</code> type and returns it.
Expand All @@ -112,6 +197,22 @@ public static async Task<HttpStatusCode> PostJsonAsync<TRequest>(
return client.PutAsync<TResponse>(restRequest, cancellationToken);
}

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter.
/// Expects no response back, just the status code.
/// </summary>
/// <param name="client">RestClient instance</param>
/// <param name="resource">Resource URL</param>
/// <param name="request">Request object, must be serializable to JSON</param>
/// <typeparam name="TRequest">Request object type</typeparam>
/// <returns>Response status code</returns>
public static HttpStatusCode PutJson<TRequest>(
this RestClient client,
string resource,
TRequest request
) where TRequest : class
=> AsyncHelpers.RunSync(() => client.PutJsonAsync(resource, request));

/// <summary>
/// Serializes the <code>request</code> object to JSON and makes a PUT call to the resource specified in the <code>resource</code> parameter.
/// Expects no response back, just the status code.
Expand Down
Loading