Skip to content

Commit

Permalink
feat: added feign client to connect this api to perustars-ml-service api
Browse files Browse the repository at this point in the history
  • Loading branch information
Miguel445Ar committed Nov 12, 2023
1 parent 06345b2 commit 4541d99
Show file tree
Hide file tree
Showing 11 changed files with 142 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace PERUSTARS.DataAnalytics.Application.Jobs
{
public class DataAnalyticsJob : IHostedService, IDisposable
{
private readonly IServiceProvider _serviceProvider;
private Timer _timer;
private readonly PeruStarsMLServiceFeignClient _peruStarsMLServiceFeignClient;
private readonly ILogger<DataAnalyticsJob> _logger;

public DataAnalyticsJob(IServiceProvider serviceProvider, PeruStarsMLServiceFeignClient peruStarsMLServiceFeignClient)
{
_serviceProvider = serviceProvider;
_peruStarsMLServiceFeignClient = peruStarsMLServiceFeignClient;
using var scope = _serviceProvider.CreateScope();
_logger = scope.ServiceProvider.GetRequiredService<ILogger<DataAnalyticsJob>>();
}

private async void ComputeRecommendationData(object state)
{
bool isSuccess = await _peruStarsMLServiceFeignClient.ComputeRecommendationSystem();
if (isSuccess) _logger.LogInformation("Remote call to perustars-ml-api was successfully executed");
else _logger.LogInformation("Remote call to perustars-ml-api failed");
}

public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting Data Analytics Scheduled Job");
_timer = new Timer(ComputeRecommendationData, null, TimeSpan.Zero, TimeSpan.FromHours(5));
return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping Data Analytics Scheduled Job");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose() => _timer.Dispose();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using Microsoft.Extensions.Logging;
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients.Resources;
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients.Resources.Dto;
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients.Resources.Response;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace PERUSTARS.DataAnalytics.Infrastructure.FeignClients
{
public class PeruStarsMLServiceFeignClient
{
private readonly HttpClient _httpClient;
private readonly ILogger<PeruStarsMLServiceFeignClient> _logger;

public PeruStarsMLServiceFeignClient(HttpClient httpClient, ILogger<PeruStarsMLServiceFeignClient> logger)
{
_httpClient = httpClient;
_logger = logger;
_httpClient.BaseAddress = new Uri("https://perustars-ml-service.onrender.com");
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<bool> ComputeRecommendationSystem()
{
HttpResponseMessage response = await _httpClient.GetAsync("/recommendation-system/compute-data");
if (!response.IsSuccessStatusCode) return false;
string message = await response.Content.ReadAsStringAsync();
_logger.LogInformation("Result from ml-api: {}", message);
return true;
}
public async Task<MLResponse> GetHobbyistRecommendedArtist(long hobbyistId)
{
string path = $"/recommendation-system/hobbyists/{hobbyistId}/recommended-artists";
_logger.LogInformation($"Calling endpoint {path} from perustars-ml-service");
HttpResponseMessage response = await _httpClient.GetAsync(path);
if (!response.IsSuccessStatusCode)
{
_logger.LogInformation("Something went wrong when calling perustars-ml-api");
return new MLResponse { Data = null, statusCode = HttpStatusCode.InternalServerError };
}
MLDto data = await response.Content.ReadFromJsonAsync<MLDto>();
_logger.LogInformation("API call to {} done successfully", path);
return new MLResponse { Data = data, statusCode = HttpStatusCode.OK };
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace PERUSTARS.DataAnalytics.Infrastructure.FeignClients.Resources.Dto
{
public class MLDto
{
public long? ArtistId { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients.Resources.Dto;
using System.Net;

namespace PERUSTARS.DataAnalytics.Infrastructure.FeignClients.Resources.Response
{
public class MLResponse
{
public MLDto? Data { get; set; }

Check warning on line 8 in PERUSTARS/PERUSTARS/DataAnalytics/Infrastructure/FeignClients/Resources/Response/MLResponse.cs

View workflow job for this annotation

GitHub Actions / build

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
public HttpStatusCode statusCode { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
using Microsoft.AspNetCore.Mvc;
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients;
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients.Resources.Response;
using System.Threading.Tasks;
using System.Net;

namespace PERUSTARS.DataAnalytics.Interface.REST
{
[ApiController]
[Route("/data-analytics")]
public class DataAnalyticsController : ControllerBase
{
[HttpGet(Name = "/hobbyists/{hobbyistId}/favourites-artists")]
public IActionResult GetFavouristArtistsFrom(long hobbyistId)
private readonly PeruStarsMLServiceFeignClient _peruStarsMLServiceFeignClient;

public DataAnalyticsController(PeruStarsMLServiceFeignClient peruStarsMLServiceFeignClient)
{
_peruStarsMLServiceFeignClient = peruStarsMLServiceFeignClient;
}

return Ok();
[HttpGet(Name = "/hobbyists/{hobbyistId}/recommended-artists")]
public async Task<IActionResult> GetFavouristArtistsFrom(long hobbyistId)
{
MLResponse result = await _peruStarsMLServiceFeignClient.GetHobbyistRecommendedArtist(hobbyistId);
if(result.statusCode == HttpStatusCode.InternalServerError)
{
return StatusCode((int)HttpStatusCode.InternalServerError, "An error ocurred while trying to call perustars-ml-service");
}
return Ok(result);
}
}
}
2 changes: 0 additions & 2 deletions PERUSTARS/PERUSTARS/PERUSTARS.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,8 @@
<Folder Include="ConductsReportsManagement\Domain\Services\" />
<Folder Include="ArtworkManagement\Application\Events\Services\" />
<Folder Include="ArtworkManagement\Domain\Model\Aggregates\" />
<Folder Include="DataAnalytics\Application\Jobs\" />
<Folder Include="DataAnalytics\Domain\Model\Aggregates\" />
<Folder Include="DataAnalytics\Domain\Model\Events\" />
<Folder Include="DataAnalytics\Infrastructure\FeignClients\" />
<Folder Include="ProfileManagement\Application\Commands\" />
<Folder Include="IdentityAndAccountManagement\Infrastructure\Context\" />

Expand Down
2 changes: 1 addition & 1 deletion PERUSTARS/PERUSTARS/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5001;http://localhost:5000",
"applicationUrl": "http://localhost:5001;http://localhost:5002",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
Expand Down
7 changes: 6 additions & 1 deletion PERUSTARS/PERUSTARS/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
using PERUSTARS.DataAnalytics.Domain.Services;
using PERUSTARS.DataAnalytics.Application.Commands.Services;
using Microsoft.Extensions.Logging;
using PERUSTARS.DataAnalytics.Application.Jobs;
using PERUSTARS.DataAnalytics.Infrastructure.FeignClients;

namespace PERUSTARS
{
Expand Down Expand Up @@ -150,6 +152,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddScoped<IMLTrainingDataRepository, MLTrainingDataRepository>();
services.AddScoped<IDataAnalyticsCommandService, DataAnalyticsCommandService>();
services.AddTransient<DataAnalyticsFacade>();
services.AddTransient<PeruStarsMLServiceFeignClient>();

// Apply Endpoints Naming Convention
services.AddRouting(options => options.LowercaseUrls = true);
Expand All @@ -171,7 +174,9 @@ public void ConfigureServices(IServiceCollection services)
c.SwaggerDoc("v1", new OpenApiInfo { Title = "PERUSTARS", Version = "v1" });
c.EnableAnnotations();
});


services.AddHttpClient();
services.AddHostedService<DataAnalyticsJob>();

}

Expand Down
Binary file modified PERUSTARS/PERUSTARS/bin/Debug/net5.0/PERUSTARS.dll
Binary file not shown.
Binary file modified PERUSTARS/PERUSTARS/bin/Debug/net5.0/PERUSTARS.pdb
Binary file not shown.
2 changes: 1 addition & 1 deletion PERUSTARS/PERUSTARS/bin/Debug/net5.0/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"ConnectionStrings": {

//"DefaultConnection1": "server=localhost;port=3306;database=perustars;uid=root;password=admin",
//"DefaultConnection1ssssss": "server=localhost;port=3306;database=perustars;uid=root;password=admin",
//"DefaultConnection": "server=perustars-db.mysql.database.azure.com;port=3306;database=perustars;uid=perustarsAdmin;password=Miguel445"
//"DefaultConnection3": "Server=MYSQL5047.site4now.net;Database=db_a758df_perusta;Uid=a758df_perusta;Pwd=password1",
"DefaultConnection": "Server=bufyroukqdunhwcivvpo-mysql.services.clever-cloud.com;Database=bufyroukqdunhwcivvpo;Uid=ubcldvvxbrtlhp2d;Pwd=FltJthiJHLXaKDmKT11O"
Expand Down

0 comments on commit 4541d99

Please sign in to comment.