Skip to content

Commit

Permalink
Implement conductor client with Http client
Browse files Browse the repository at this point in the history
  • Loading branch information
renatohalic97 committed Sep 7, 2023
1 parent b6a243b commit 8df5f7f
Show file tree
Hide file tree
Showing 8 changed files with 165 additions and 7 deletions.
5 changes: 4 additions & 1 deletion examples/ConductorSharp.ApiEnabled/ConductorModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ protected override void Load(ContainerBuilder builder)

private static void RegisterTasks(ContainerBuilder builder)
{
builder.RegisterWorkerTask<PrepareEmailHandler>();
builder.RegisterWorkerTask<PrepareEmailHandler>(options =>
{
options.OwnerEmail = "[email protected]";
});
}

private static void RegisterWorkflows(ContainerBuilder builder) { }
Expand Down
4 changes: 2 additions & 2 deletions examples/ConductorSharp.Definitions/ConductorModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ protected override void Load(ContainerBuilder builder)
base.Load(builder);

builder.RegisterWorkflow<SendCustomerNotification>();
builder.RegisterWorkflow<HandleNotificationFailure>();
builder.RegisterWorkflow<CSharpLambdaWorkflow>();
/* builder.RegisterWorkflow<HandleNotificationFailure>();
builder.RegisterWorkflow<CSharpLambdaWorkflow>();*/
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@
</PropertyGroup>

<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
</ItemGroup>

<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
Expand Down
5 changes: 4 additions & 1 deletion examples/ConductorSharp.NoApi/ConductorModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ protected override void Load(ContainerBuilder builder)

private static void RegisterTasks(ContainerBuilder builder)
{
builder.RegisterWorkerTask<GetCustomerHandler>();
builder.RegisterWorkerTask<GetCustomerHandler>(options =>
{
options.OwnerEmail = "[email protected]";
});
}

private static void RegisterWorkflows(ContainerBuilder builder) { }
Expand Down
3 changes: 2 additions & 1 deletion src/ConductorSharp.Client/RestConfig.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using RestSharp;
using System;
using System.Collections.Generic;

namespace ConductorSharp.Client
{
Expand All @@ -9,7 +10,7 @@ public class RestConfig
public string ApiPath { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public Func<RestClient> CreateClient { get; set; }
public Dictionary<string, string> DefaultHeaders { get; set; }
public bool IgnoreValidationErrors { get; set; }
}
}
139 changes: 139 additions & 0 deletions src/ConductorSharp.Client/Service/ConductorHttpClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
using ConductorSharp.Client.Exceptions;
using ConductorSharp.Client.Model.Response;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using JsonSerializer = Newtonsoft.Json.JsonSerializer;

namespace ConductorSharp.Client.Service
{
public class ConductorHttpClient : IConductorClient
{
private readonly ILogger<ConductorClient> _logger;
private readonly HttpClient _httpClient;
private readonly RestConfig _restConfig;

public ConductorHttpClient(ILogger<ConductorClient> logger, HttpClient httpClient, RestConfig restConfig)
{
_logger = logger;
_httpClient = httpClient;
_restConfig = restConfig;
}

private async void CheckResponse(HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
var request = await response.RequestMessage.Content.ReadAsStringAsync();
var responseContent = await response.Content.ReadAsStringAsync();
ConductorErrorResponse error = default;

_logger.LogDebug("Received {@response}", response.Content);

error = JsonConvert.DeserializeObject<ConductorErrorResponse>(responseContent);

if (error == null || string.IsNullOrEmpty(error.Message))
throw new Exception("Unable to deserialize error");

_logger.LogError("{@conductorError}", error);

if (!_restConfig.IgnoreValidationErrors && error?.Message?.Contains("Validation failed") == true)
throw new Exception(responseContent);

if (response.StatusCode == HttpStatusCode.InternalServerError)
throw new Exception(responseContent);

if (response.StatusCode == HttpStatusCode.NotFound)
throw new NotFoundException(error.Message);
}
}

private HttpRequestMessage CreateRequest(Uri relativeUrl, HttpMethod method, object body = null)
{
Uri uri;

if (relativeUrl.IsAbsoluteUri)
uri = relativeUrl;
else
uri = new Uri($"{_restConfig.BaseUrl}/{_restConfig.ApiPath}/{relativeUrl.OriginalString}");

var httpRequestMessage = new HttpRequestMessage(method, uri);

if (body != null)
httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");

return httpRequestMessage;
}

public async Task<T> ExecuteRequestAsync<T>(Uri relativeUrl, HttpMethod method, object resource)
{
var request = CreateRequest(relativeUrl, method, resource);
var response = await _httpClient.SendAsync(request);

CheckResponse(response);

return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}

public async Task<T> ExecuteRequestAsync<T>(Uri relativeUrl, HttpMethod method)
{
var request = CreateRequest(relativeUrl, method);

var response = await _httpClient.SendAsync(request);

CheckResponse(response);

return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}

public async Task ExecuteRequestAsync(Uri relativeUrl, HttpMethod method, object resource)
{
var request = CreateRequest(relativeUrl, method, resource);
var response = await _httpClient.SendAsync(request);

CheckResponse(response);
}

public async Task ExecuteRequestAsync(Uri relativeUrl, HttpMethod method)
{
var request = CreateRequest(relativeUrl, method);
var response = await _httpClient.SendAsync(request);

CheckResponse(response);
}

public async Task<T> ExecuteRequestAsync<T>(Uri relativeUrl, HttpMethod method, object resource, Dictionary<string, string> headers)
{
var request = CreateRequest(relativeUrl, method, resource);

foreach (var header in headers)
request.Headers.Add(header.Key, header.Value);

var response = await _httpClient.SendAsync(request);

CheckResponse(response);

return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}

public async Task<string> ExecuteRequestAsync(Uri relativeUrl, HttpMethod method, object resource, Dictionary<string, string> headers)
{
var request = CreateRequest(relativeUrl, method, resource);

foreach (var header in headers)
request.Headers.Add(header.Key, header.Value);

var response = await _httpClient.SendAsync(request);

CheckResponse(response);

return await response.Content.ReadAsStringAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using ConductorSharp.Engine.Util.Builders;
using RestSharp;
using System;
using System.Net.Http;

namespace ConductorSharp.Engine.Extensions
{
Expand All @@ -29,7 +30,9 @@ public static IConductorSharpBuilder AddConductorSharp(
}
);

builder.RegisterType<ConductorClient>().As<IConductorClient>().SingleInstance();
builder.RegisterType<HttpClient>().AsSelf();

builder.RegisterType<ConductorHttpClient>().As<IConductorClient>().SingleInstance();

builder.RegisterType<TaskService>().As<ITaskService>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ public static IExecutionManagerBuilder AddCSharpLambdaTasks(
string csharpLambdaTaskNamePrefix = null
)
{
executionManagerBuilder.Builder.RegisterWorkerTask<CSharpLambdaTask>();
executionManagerBuilder.Builder.RegisterWorkerTask<CSharpLambdaTask>(options =>
{
options.OwnerEmail = "[email protected]";
});
executionManagerBuilder.Builder.RegisterMediatR(typeof(CSharpLambdaTask).Assembly);
executionManagerBuilder.Builder.RegisterInstance(
new ConfigurationProperty(CSharpLambdaTask.LambdaTaskNameConfigurationProperty, csharpLambdaTaskNamePrefix)
Expand Down

0 comments on commit 8df5f7f

Please sign in to comment.