Skip to content
This repository has been archived by the owner on Apr 27, 2024. It is now read-only.

Feature/rabbitmq #99

Merged
merged 8 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
3 changes: 2 additions & 1 deletion k8s/apply-all.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ kubectl apply -f hpas/techlanches-api-hpa.yaml
kubectl apply -f hpas/techlanches-worker-hpa.yaml
kubectl apply -f ./deployments/techlanches-sql-deployment.yaml
kubectl apply -f ./deployments/techlanches-api-deployment.yaml
kubectl apply -f ./deployments/techlanches-worker-deployment.yaml
kubectl apply -f ./deployments/techlanches-worker-deployment.yaml
kubectl apply -f ./deployments/techlanches-rabbitmq-deployment.yaml
71 changes: 71 additions & 0 deletions k8s/deployments/techlanches-rabbitmq-deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
apiVersion: v1
kind: Service
metadata:
name: rabbitmq
namespace: techlanches
spec:
ports:
- port: 5672
name: amqp
- port: 15672
name: http
selector:
app: rabbitmq
type: LoadBalancer

---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: rabbitmq
namespace: techlanches
spec:
serviceName: "rabbitmq"
replicas: 1
selector:
matchLabels:
app: rabbitmq
template:
metadata:
labels:
app: rabbitmq
spec:
hostname: techlanches
containers:
- name: rabbitmq
image: rabbitmq:management
ports:
- containerPort: 5672
- containerPort: 15672
env:
- name: RABBITMQ_DEFAULT_USER
valueFrom:
secretKeyRef:
name: techlanches-secrets
key: RABBITMQ_DEFAULT_USER
- name: RABBITMQ_DEFAULT_PASS
valueFrom:
secretKeyRef:
name: techlanches-secrets
key: RABBITMQ_DEFAULT_PASS
volumeMounts:
- name: rabbit-data
mountPath: /var/lib/rabbitmq/mnesia

volumes:
- name: rabbit-data
persistentVolumeClaim:
claimName: rabbit-data

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: rabbit-data
namespace: techlanches
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
2 changes: 1 addition & 1 deletion k8s/deployments/techlanches-sql-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ spec:
containers:
- name: sql-server
image: mcr.microsoft.com/mssql/server:2019-latest
imagePullPolicy: Always
# imagePullPolicy: Always
Copy link
Collaborator

Choose a reason for hiding this comment

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

linha comentada

ports:
- containerPort: 1433
env:
Expand Down
4 changes: 3 additions & 1 deletion k8s/techlanches-secrets.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ metadata:
type: Opaque
data:
DefaultConnection: c2VydmVyPXRlY2hsYW5jaGVzLXNxbC1zZXJ2aWNlO3VzZXIgaWQ9c2E7cGFzc3dvcmQ9UXdlcnR5QDEyMzQ1O2RhdGFiYXNlPXRlY2hsYW5jaGVzO3RydXN0U2VydmVyQ2VydGlmaWNhdGU9dHJ1ZTs=
SA_PASSWORD: UXdlcnR5QDEyMzQ1 # Qwerty@12345
SA_PASSWORD: UXdlcnR5QDEyMzQ1 # Qwerty@12345
RABBITMQ_DEFAULT_USER: cmFiYml0 # rabbit
RABBITMQ_DEFAULT_PASS: cmFiYml0cGFzc3dvcmQ= # rabbitpassword
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TechLanches.Adapter.ACL.Pagamento.QrCode.Constantes
{
public static class MercadoPagoConstantes
{
public const string MERCADO_PAGO = "MercadoPago";
public const string STATUS_APROVADO = "approved";
public const string STATUS_REPROVADO = "repproved";
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using TechLanches.Adapter.ACL.Pagamento.QrCode.DTOs;

namespace TechLanches.Adapter.ACL.Pagamento.QrCode.Provedores.MercadoPago
namespace TechLanches.Adapter.ACL.Pagamento.QrCode.Provedores.MercadoPago
{
public interface IMercadoPagoService : IPagamentoACLService
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using TechLanches.Adapter.ACL.Pagamento.QrCode.DTOs;
using TechLanches.Adapter.ACL.Pagamento.QrCode.Constantes;
using TechLanches.Adapter.ACL.Pagamento.QrCode.DTOs;

namespace TechLanches.Adapter.ACL.Pagamento.QrCode.Provedores.MercadoPago
{
Expand All @@ -24,16 +25,16 @@ public Task<string> GerarPagamentoEQrCode(string pedidoMercadoPago, string usuar
private string ObterStatusPagamentoSimulado()
{
Random random = new Random();
string[] statuses = { "approved", "repproved" };
string[] statuses = { MercadoPagoConstantes.STATUS_APROVADO, MercadoPagoConstantes.STATUS_REPROVADO };
return statuses[random.Next(statuses.Length)];
}

private StatusPagamentoEnum ConverterResultadoParaEnum(string statusStr)
{
return statusStr.ToLower() switch
{
"approved" => StatusPagamentoEnum.Aprovado,
"repproved" => StatusPagamentoEnum.Reprovado,
MercadoPagoConstantes.STATUS_APROVADO => StatusPagamentoEnum.Aprovado,
MercadoPagoConstantes.STATUS_REPROVADO => StatusPagamentoEnum.Reprovado,
_ => throw new ArgumentException("String de status pagamento inválida"),
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Newtonsoft.Json;
using System.Net.Http.Json;
using System.Text;
using TechLanches.Adapter.ACL.Pagamento.QrCode.Constantes;
using TechLanches.Adapter.ACL.Pagamento.QrCode.DTOs;
using TechLanches.Adapter.ACL.Pagamento.QrCode.Models;

Expand All @@ -9,9 +10,9 @@ namespace TechLanches.Adapter.ACL.Pagamento.QrCode.Provedores.MercadoPago
public class MercadoPagoService : IMercadoPagoService
{
private readonly HttpClient _httpClient;
public MercadoPagoService(HttpClient httpClient)
public MercadoPagoService(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClient;
_httpClient = httpClientFactory.CreateClient(MercadoPagoConstantes.MERCADO_PAGO);
}

public async Task<PagamentoResponseACLDTO> ConsultarPagamento(string idPagamentoComercial)
Expand Down Expand Up @@ -42,8 +43,8 @@ private StatusPagamentoEnum ConverterResultadoParaEnum(string statusStr)
{
return statusStr.ToLower() switch
{
"approved" => StatusPagamentoEnum.Aprovado,
"repproved" => StatusPagamentoEnum.Reprovado,
MercadoPagoConstantes.STATUS_APROVADO => StatusPagamentoEnum.Aprovado,
MercadoPagoConstantes.STATUS_REPROVADO => StatusPagamentoEnum.Reprovado,
_ => throw new ArgumentException("String de status pagamento inválida"),
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using TechLanches.Adapter.ACL.Pagamento.QrCode.Provedores.MercadoPago;
using TechLanches.Adapter.RabbitMq.Messaging;
using TechLanches.Adapter.SqlServer.Repositories;
using TechLanches.Application.Ports.Repositories;
using TechLanches.Application.Ports.Services;
Expand Down Expand Up @@ -36,6 +37,7 @@ public static void AddDependencyInjectionConfiguration(this IServiceCollection s
services.AddScoped<IPedidoRepository, PedidoRepository>();
services.AddScoped<IProdutoRepository, ProdutoRepository>();
services.AddScoped<IPagamentoRepository, PagamentoRepository>();
services.AddScoped<IRabbitMqService, RabbitMqService>();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using TechLanches.Adapter.API.Health;

namespace TechLanches.Adapter.API.Configuration
{
Expand All @@ -7,7 +8,8 @@ public static class HealthCheckConfig
public static void AddHealthCheckConfig(this IServiceCollection services, IConfiguration configuration)
{
services.AddHealthChecks()
.AddSqlServer(connectionString: configuration.GetConnectionString("DefaultConnection"), name: "Banco de dados Tech Lanches");
.AddSqlServer(connectionString: configuration.GetConnectionString("DefaultConnection"), name: "Banco de dados Tech Lanches")
.AddCheck<RabbitMQHealthCheck>("rabbit_hc");
}

public static void AddHealthCheckEndpoint(this IApplicationBuilder app)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using Swashbuckle.AspNetCore.Annotations;
using TechLanches.Application.DTOs;
using TechLanches.Application.Ports.Services.Interfaces;
using TechLanches.Adapter.ACL.Pagamento.QrCode.Provedores.MercadoPago;

namespace TechLanches.Adapter.API.Endpoints
{
Expand All @@ -24,7 +23,6 @@ public static void MapCheckoutEndpoints(this IEndpointRouteBuilder app)
public static async Task<IResult> Checkout(
int pedidoId,
[FromServices] ICheckoutService checkoutService,
IPagamentoACLService pagamentoQrCodeACLService,
IPedidoService pedidoService)
{

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
using System.Net;
using TechLanches.Adapter.ACL.Pagamento.QrCode.DTOs;
using TechLanches.Adapter.API.Constantes;
using TechLanches.Adapter.RabbitMq.Messaging;
using TechLanches.Application.DTOs;
using TechLanches.Application.Ports.Services.Interfaces;
using TechLanches.Domain.Enums;

namespace TechLanches.Adapter.API.Endpoints
{
Expand Down Expand Up @@ -45,7 +47,7 @@ private static async Task<IResult> BuscarStatusPagamentoPorPedidoId([FromRoute]
return Results.Ok(pagamento.Adapt<PagamentoStatusResponseDTO>());
}

private static async Task<IResult> BuscarPagamento(int id, TopicACL topic, [FromServices] IPagamentoService pagamentoService)
private static async Task<IResult> BuscarPagamento(int id, TopicACL topic, [FromServices] IPagamentoService pagamentoService, [FromServices] IPedidoService pedidoService)
{
if (topic == TopicACL.merchant_order)
{
Expand All @@ -54,21 +56,33 @@ private static async Task<IResult> BuscarPagamento(int id, TopicACL topic, [From
if (pagamentoExistente is null)
return Results.NotFound(new ErrorResponseDTO { MensagemErro = $"Nenhum pedido encontrado para o id: {id}", StatusCode = HttpStatusCode.NotFound });

await pagamentoService.RealizarPagamento(pagamentoExistente.PedidoId, pagamentoExistente.StatusPagamento);
var pagamento = await pagamentoService.RealizarPagamento(pagamentoExistente.PedidoId, pagamentoExistente.StatusPagamento);

if (pagamento)
await pedidoService.TrocarStatus(pagamentoExistente.PedidoId, StatusPedido.PedidoRecebido);
else
await pedidoService.TrocarStatus(pagamentoExistente.PedidoId, StatusPedido.PedidoCancelado);
}
return Results.Ok();
}

private static async Task<IResult> BuscarPagamentoMockado(int pedidoId, [FromServices] IPagamentoService pagamentoService)
private static async Task<IResult> BuscarPagamentoMockado(int pedidoId, [FromServices] IPagamentoService pagamentoService, [FromServices] IPedidoService pedidoService)
{
var pagamentoExistente = await pagamentoService.ConsultarPagamentoMockado(pedidoId.ToString());

var pagamento = await pagamentoService.RealizarPagamento(pedidoId, pagamentoExistente.StatusPagamento);

if (pagamento)
{
await pedidoService.TrocarStatus(pedidoId, StatusPedido.PedidoRecebido);
return Results.Ok();
}
else
return Results.BadRequest(new ErrorResponseDTO { MensagemErro = $"Erro ao realizar o pagamento.", StatusCode = HttpStatusCode.NotFound });
{
await pedidoService.TrocarStatus(pedidoId, StatusPedido.PedidoCancelado);
return Results.BadRequest(new ErrorResponseDTO { MensagemErro = $"Erro ao realizar o pagamento.", StatusCode = HttpStatusCode.BadRequest });
}

}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using RabbitMQ.Client;

namespace TechLanches.Adapter.API.Health
{
public class RabbitMQHealthCheck : IHealthCheck
{
private readonly string _rabbitHost;
private readonly string _rabbitUser;
private readonly string _rabbitPassword;

public RabbitMQHealthCheck(IConfiguration configuration)
{
_rabbitHost = configuration.GetSection("RabbitMQ:Host").Value;
_rabbitUser = configuration.GetSection("RabbitMQ:User").Value;
_rabbitPassword = configuration.GetSection("RabbitMQ:Password").Value;
}

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
var factory = new ConnectionFactory { HostName = _rabbitHost, UserName = _rabbitUser, Password = _rabbitPassword };

using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
// Verifica se a conexão e o canal com o RabbitMQ podem ser estabelecidos
if (connection.IsOpen && channel.IsOpen)
{
return HealthCheckResult.Healthy("RabbitMQ is reachable.");
}
else
{
return HealthCheckResult.Unhealthy("Unable to connect to RabbitMQ.");
}
}
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy($"Exception during RabbitMQ health check: {ex.Message}");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using Polly;
using Polly.Extensions.Http;
using System.Net.Http.Headers;
using TechLanches.Adapter.ACL.Pagamento.QrCode.Provedores.MercadoPago;
using TechLanches.Adapter.API.Configuration;
using TechLanches.Adapter.RabbitMq.Options;
using TechLanches.Adapter.SqlServer;
using TechLanches.Application;

Expand Down Expand Up @@ -30,6 +30,7 @@
//Setting mapster
builder.Services.RegisterMaps();

builder.Services.Configure<RabbitOptions>(builder.Configuration.GetSection("RabbitMQ"));

//Setting healthcheck
builder.Services.AddHealthCheckConfig(builder.Configuration);
Expand All @@ -39,13 +40,12 @@
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));

//Registrar httpclient
builder.Services.AddHttpClient<IPagamentoACLService, MercadoPagoService>((serviceProvider, httpClient) =>
builder.Services.AddHttpClient("MercadoPago", httpClient =>
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", builder.Configuration.GetSection($"ApiMercadoPago:{AppSettings.GetEnv()}")["AccessToken"]);
httpClient.BaseAddress = new Uri(builder.Configuration.GetSection($"ApiMercadoPago:{AppSettings.GetEnv()}")["BaseUrl"]);
})
.AddPolicyHandler(retryPolicy);
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", builder.Configuration.GetSection($"ApiMercadoPago:AccessToken").Value);
httpClient.BaseAddress = new Uri(builder.Configuration.GetSection($"ApiMercadoPago:BaseUrl").Value);
}).AddPolicyHandler(retryPolicy);

var app = builder.Build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

<ItemGroup>
<ProjectReference Include="..\..\..\Core\TechLanches.Application\TechLanches.Application.csproj" />
<ProjectReference Include="..\..\..\TechLanches.Adapter.RabbitMq\TechLanches.Adapter.RabbitMq.csproj" />
<ProjectReference Include="..\..\Driven\TechLanches.Adapter.SqlServer\TechLanches.Adapter.SqlServer.csproj" />
</ItemGroup>

Expand Down
Loading
Loading