Skip to content

Commit

Permalink
fix: fix several bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
foxminchan committed Sep 14, 2024
1 parent d928653 commit 12b9dc4
Show file tree
Hide file tree
Showing 116 changed files with 465 additions and 1,884 deletions.
23 changes: 11 additions & 12 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<XabarilVersion>8.0.1</XabarilVersion>
<ApiVersioningVersion>8.1.0</ApiVersioningVersion>
<PollyVersion>8.4.1</PollyVersion>
<AspireUnstablePackagesVersion>8.0.2-preview.1.24326.4</AspireUnstablePackagesVersion>
<AspireUnstablePackagesVersion>8.2.0-preview.1.24428.5</AspireUnstablePackagesVersion>
<GrpcVersion>2.65.0</GrpcVersion>
<MassTransitVersion>8.2.5</MassTransitVersion>
</PropertyGroup>
Expand All @@ -22,13 +22,12 @@
<PackageVersion Include="Aspire.Hosting.PostgreSQL" Version="$(AspireVersion)" />
<PackageVersion Include="Aspire.Hosting.RabbitMQ" Version="$(AspireVersion)" />
<PackageVersion Include="Aspire.Hosting.Redis" Version="$(AspireVersion)" />
<PackageVersion Include="Aspire.Npgsql" Version="$(AspireVersion)" />
<PackageVersion Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="$(AspireVersion)" />
<PackageVersion Include="Aspire.Azure.Storage.Blobs" Version="$(AspireVersion)" />
<PackageVersion Include="Aspire.Azure.AI.OpenAI" Version="$(AspireUnstablePackagesVersion)" />
<PackageVersion Include="Aspire.StackExchange.Redis" Version="$(AspireVersion)" />
<PackageVersion Include="Aspire.StackExchange.Redis.OutputCaching" Version="$(AspireVersion)" />
<PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="$(MicrosoftExtensionsVersion)" />
<PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="8.9.1" />
<PackageVersion Include="Microsoft.Extensions.ServiceDiscovery" Version="$(AspireVersion)" />
<!-- Aspirant -->
<PackageVersion Include="Aspirant.Hosting" Version="$(AspirantVersion)" />
Expand All @@ -47,20 +46,19 @@
<PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="$(AspnetVersion)" />
<PackageVersion Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="$(AspnetVersion)" />
<!-- Entity Framework Core -->
<PackageVersion Include="Pgvector" Version="0.3.0" />
<PackageVersion Include="Pgvector.EntityFrameworkCore" Version="0.2.1" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="$(EfCoreVersion)" />
<PackageVersion Include="EFCore.NamingConventions" Version="8.0.3" />
<PackageVersion Include="EntityFrameworkCore.Exceptions.Common" Version="8.1.3" />
<PackageVersion Include="EntityFrameworkCore.Exceptions.PostgreSQL" Version="8.1.3" />
<!-- Semantic Kernel -->
<PackageVersion Include="Microsoft.SemanticKernel" Version="1.17.2" />
<PackageVersion Include="Microsoft.SemanticKernel" Version="1.19.0" />
<!-- Polly -->
<PackageVersion Include="Polly" Version="$(PollyVersion)" />
<PackageVersion Include="Polly.Extensions" Version="$(PollyVersion)" />
<!-- Ardalis -->
<PackageVersion Include="Ardalis.GuardClauses" Version="4.6.0" />
<PackageVersion Include="Ardalis.Result.AspNetCore" Version="9.1.0" />
<PackageVersion Include="Ardalis.Result.AspNetCore" Version="10.0.0" />
<PackageVersion Include="Ardalis.Specification" Version="8.0.0" />
<PackageVersion Include="Ardalis.Specification.EntityFrameworkCore" Version="8.0.0" />
<!-- OpenTelemetry -->
Expand All @@ -80,11 +78,11 @@
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageVersion Include="Xunit.Combinatorial" Version="1.6.24" />
<PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
<PackageVersion Include="Moq" Version="4.20.70" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageVersion Include="Moq" Version="4.20.72" />
<PackageVersion Include="FluentAssertions" Version="7.0.0-alpha.4" />
<PackageVersion Include="ReportGenerator" Version="5.3.8" />
<PackageVersion Include="WireMock.Net.Aspire" Version="1.6.1" />
<PackageVersion Include="ReportGenerator" Version="5.3.9" />
<PackageVersion Include="WireMock.Net.Aspire" Version="1.6.3" />
<!-- Grpc -->
<PackageVersion Include="Grpc.AspNetCore" Version="$(GrpcVersion)" />
<PackageVersion Include="Grpc.AspNetCore.Server.ClientFactory" Version="$(GrpcVersion)" />
Expand All @@ -96,8 +94,9 @@
<PackageVersion Include="MassTransit.EntityFrameworkCore" Version="$(MassTransitVersion)" />
<!-- Miscellaneous -->
<PackageVersion Include="Scrutor" Version="4.2.2" />
<PackageVersion Include="MediatR" Version="12.4.0" />
<PackageVersion Include="Marten.AspNetCore" Version="7.26.4" />
<PackageVersion Include="MediatR" Version="12.4.1" />
<PackageVersion Include="MongoDB.Bson" Version="2.28.0" />
<PackageVersion Include="Marten.AspNetCore" Version="7.27.0" />
<PackageVersion Include="FluentEmail.Mailtrap" Version="2.7.0" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.7.3" />
<PackageVersion Include="FluentValidation.AspNetCore" Version="11.3.0" />
Expand Down
4 changes: 2 additions & 2 deletions src/BookWorm.Basket/BookWorm.Basket.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
</ItemGroup>

<ItemGroup>
<Protobuf Include="Proto\basket.proto" GrpcServices="Server" />
<Protobuf Include="..\BookWorm.Catalog\Proto\book.proto" GrpcServices="Client" />
<Protobuf Include="Protos\basket.proto" GrpcServices="Server" />
<Protobuf Include="..\BookWorm.Catalog\Protos\book.proto" Link="Protos\book.proto" GrpcServices="Client" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 3 additions & 1 deletion src/BookWorm.Basket/Extensions/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ internal static class Extensions
{
public static void AddApplicationServices(this IHostApplicationBuilder builder)
{
builder.AddServiceDefaults();

builder.Services.AddExceptionHandler<ValidationExceptionHandler>();
builder.Services.AddExceptionHandler<NotFoundExceptionHandler>();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
Expand Down Expand Up @@ -40,12 +42,12 @@ public static void AddApplicationServices(this IHostApplicationBuilder builder)
builder.Services.AddSingleton<IBookService, BookService>();

builder.Services.AddGrpc();

builder.Services.AddGrpcClient<GrpcBookClient>(o =>
{
o.Address = new("https+http://catalog-api");
});

builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<IIdentityService, IdentityService>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Security.Claims;

namespace BookWorm.Basket.Extensions;

internal static class ServerCallContextIdentityExtensions
{
public static string? GetUserIdentity(this ServerCallContext context)
{
return context.GetHttpContext().User.FindFirst(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
}

public static string? GetUserName(this ServerCallContext context)
{
return context.GetHttpContext().User.FindFirst(x => x.Type == ClaimTypes.Name)?.Value;
}
}
1 change: 0 additions & 1 deletion src/BookWorm.Basket/Features/Get/GetBasketEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ public void MapEndpoint(IEndpointRouteBuilder app)
{
app.MapGet("/baskets", async (ISender sender) => await HandleAsync(sender))
.Produces<Ok<BasketDto>>()
.ProducesProblem(StatusCodes.Status404NotFound)
.WithTags(nameof(Basket))
.WithName("Get Basket")
.MapToApiVersion(new(1, 0))
Expand Down
5 changes: 4 additions & 1 deletion src/BookWorm.Basket/Features/Get/GetBasketQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ public async Task<Result<BasketDto>> Handle(GetBasketQuery query, CancellationTo

var basket = await redisService.HashGetAsync<BasketModel?>(nameof(Basket), customerId);

Guard.Against.NotFound(customerId, basket);
if (basket is null)
{
return Result.NotFound();
}

var basketDto = new BasketDto(basket.AccountId, [], 0.0m);

Expand Down
1 change: 1 addition & 0 deletions src/BookWorm.Basket/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
global using System.Text.Json;
global using Ardalis.GuardClauses;
global using Ardalis.Result;
global using BookWorm.Basket.Extensions;
global using BookWorm.Basket.Grpc;
global using BookWorm.Basket.Infrastructure.Redis;
global using BookWorm.Constants;
Expand Down
29 changes: 13 additions & 16 deletions src/BookWorm.Basket/Grpc/BasketService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using GrpcBasketBase = BookWorm.Basket.Grpc.Basket.BasketBase;
using BasketModel = BookWorm.Basket.Domain.Basket;
using BookWorm.Basket.Features;
using BookWorm.Basket.Features.Get;
using GrpcBasketBase = BookWorm.Basket.Grpc.Basket.BasketBase;

namespace BookWorm.Basket.Grpc;

public sealed class BasketService(IRedisService redisService, IBookService bookService, ILogger<BasketService> logger)
public sealed class BasketService(ISender sender, IBookService bookService, ILogger<BasketService> logger)
: GrpcBasketBase
{
[AllowAnonymous]
Expand All @@ -15,29 +16,25 @@ public override async Task<BasketResponse> GetBasket(BasketRequest request, Serv
nameof(BasketService), nameof(GetBasket), request.BasketId);
}

var basket = await redisService.HashGetAsync<BasketModel?>(nameof(Basket), request.BasketId);
var userId = context.GetUserIdentity();

if (basket is null)
if (string.IsNullOrEmpty(userId))
{
ThrowNotFound();
return new();
}

return await MapToBasketResponse(basket);
}
var basket = await sender.Send(new GetBasketQuery());

[DoesNotReturn]
private static void ThrowNotFound()
{
throw new RpcException(new(StatusCode.NotFound, "Basket not found"));
return basket.Value is not null ? await MapToBasketResponse(basket.Value) : new();
}

private async Task<BasketResponse> MapToBasketResponse(BasketModel basket)
private async Task<BasketResponse> MapToBasketResponse(BasketDto basket)
{
var response = new BasketResponse { BasketId = basket.AccountId.ToString(), TotalPrice = 0.0 };
var response = new BasketResponse { BasketId = basket.Id.ToString(), TotalPrice = 0.0 };

foreach (var item in basket.BasketItems)
foreach (var item in basket.Items)
{
var book = await bookService.GetBookAsync(item.Id);
var book = await bookService.GetBookAsync(item.BookId);

response.Books.Add(new Book
{
Expand Down
7 changes: 2 additions & 5 deletions src/BookWorm.Basket/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using BookWorm.Basket.Extensions;
var builder = WebApplication.CreateBuilder(args);

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults()
.AddApplicationServices();
builder.AddApplicationServices();

var app = builder.Build();

Expand Down
File renamed without changes.
14 changes: 6 additions & 8 deletions src/BookWorm.Catalog/BookWorm.Catalog.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,29 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Pgvector" />
<PackageReference Include="Pgvector.EntityFrameworkCore" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
<PackageReference Include="Polly" />
<PackageReference Include="Polly.Extensions" />
<PackageReference Include="Microsoft.SemanticKernel" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Aspire.Azure.AI.OpenAI" />
<PackageReference Include="Aspire.Npgsql" />
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" />
<PackageReference Include="Aspire.Azure.Storage.Blobs" />
<PackageReference Include="Aspire.StackExchange.Redis.OutputCaching" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Polly" />
<PackageReference Include="Polly.Extensions" />
<PackageReference Include="Pgvector.EntityFrameworkCore" />
<PackageReference Include="Grpc.AspNetCore" />
<PackageReference Include="Microsoft.SemanticKernel" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" />
<PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="EntityFrameworkCore.Exceptions.PostgreSQL" />
</ItemGroup>

<ItemGroup>
<Protobuf Include="Proto\book.proto" GrpcServices="Server" />
<Protobuf Include="Protos\book.proto" GrpcServices="Server" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 4 additions & 0 deletions src/BookWorm.Catalog/Extensions/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ internal static class Extensions
{
public static void AddApplicationServices(this IHostApplicationBuilder builder)
{
builder.AddServiceDefaults();

builder.AddRedisOutputCache(ServiceName.Redis);

builder.Services.AddGrpc();
Expand Down Expand Up @@ -38,6 +40,8 @@ public static void AddApplicationServices(this IHostApplicationBuilder builder)
builder.Services.AddSingleton<CommandHandlerMetrics>();
builder.Services.AddSingleton<QueryHandlerMetrics>();

builder.Services.AddHttpContextAccessor();

builder.AddRabbitMqEventBus(typeof(global::Program), cfg =>
{
cfg.AddInMemoryInboxOutbox();
Expand Down
1 change: 0 additions & 1 deletion src/BookWorm.Catalog/Features/Books/Get/GetBookEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ public void MapEndpoint(IEndpointRouteBuilder app)
app.MapGet("/books/{id:guid}",
async (Guid id, ISender sender) => await HandleAsync(id, sender))
.Produces<Ok<BookDto>>()
.ProducesProblem(StatusCodes.Status404NotFound)
.CacheOutput(policy => policy.Expire(TimeSpan.FromMinutes(20)).SetVaryByRouteValue("id"))
.WithTags(nameof(Book))
.WithName("Get Book")
Expand Down
5 changes: 4 additions & 1 deletion src/BookWorm.Catalog/Features/Books/Get/GetBookQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ public async Task<Result<Book>> Handle(GetBookQuery request, CancellationToken c
{
var book = await repository.FirstOrDefaultAsync(new BookFilterSpec(request.Id), cancellationToken);

Guard.Against.NotFound(request.Id, book);
if (book is null)
{
return Result.NotFound();
}

return book;
}
Expand Down
2 changes: 1 addition & 1 deletion src/BookWorm.Catalog/Features/Books/List/ListBooksQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public async Task<PagedResult<IEnumerable<Book>>> Handle(ListBooksQuery request,

var books = await repository.ListAsync(spec, cancellationToken);

var totalRecords = await repository.CountAsync(spec, cancellationToken);
var totalRecords = await repository.CountAsync(cancellationToken);

var totalPages = (int)Math.Ceiling(totalRecords / (double)request.PageSize);

Expand Down
32 changes: 6 additions & 26 deletions src/BookWorm.Catalog/Grpc/BookService.cs
Original file line number Diff line number Diff line change
@@ -1,56 +1,36 @@
using BookWorm.Catalog.Domain.BookAggregate.Specifications;
using BookWorm.Catalog.Features.Books.Get;
using Grpc.Core;
using GrpcBookServer = BookWorm.Catalog.Grpc.Book.BookBase;
using BookModel = BookWorm.Catalog.Domain.BookAggregate.Book;

namespace BookWorm.Catalog.Grpc;

public sealed class BookService(IReadRepository<BookModel> repository, ILogger<BookService> logger) : GrpcBookServer
public sealed class BookService(ISender sender, ILogger<BookService> logger) : GrpcBookServer
{
[AllowAnonymous]
public override async Task<BookResponse> GetBook(BookRequest request, ServerCallContext context)
{
BookFilterSpec spec = new(Guid.Parse(request.BookId));

if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("[{Service}] - Getting book with id: {Id}", nameof(BookService), request.BookId);
}

var book = await repository.FirstOrDefaultAsync(spec);

if (book is null)
{
ThrowNotFound();
}
var book = await sender.Send(new GetBookQuery(Guid.Parse(request.BookId)), context.CancellationToken);

return MapToBookResponse(book);
return book.Value is not null ? MapToBookResponse(book.Value) : new();
}

[AllowAnonymous]
public override async Task<BookStatusResponse> GetBookStatus(BookStatusRequest request, ServerCallContext context)
{
BookFilterSpec spec = new(Guid.Parse(request.BookId));

if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("[{Service}] - Getting book status with id: {Id}", nameof(BookService), request.BookId);
}

var book = await repository.FirstOrDefaultAsync(spec);
var book = await sender.Send(new GetBookQuery(Guid.Parse(request.BookId)), context.CancellationToken);

if (book is null)
{
ThrowNotFound();
}

return MapToBookStatusResponse(book);
}

[DoesNotReturn]
private static void ThrowNotFound()
{
throw new RpcException(new(StatusCode.NotFound, "Book not found"));
return book.Value is not null ? MapToBookStatusResponse(book.Value) : new();
}

private static BookResponse MapToBookResponse(BookModel book)
Expand Down
3 changes: 0 additions & 3 deletions src/BookWorm.Catalog/Infrastructure/Ai/AiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ public async ValueTask<Vector> GetEmbeddingAsync(string text, CancellationToken

var embedding = await embeddingGenerator.GenerateEmbeddingAsync(text, cancellationToken: cancellationToken);


embedding = embedding[..EmbeddingDimensions];

if (logger.IsEnabled(LogLevel.Trace))
Expand All @@ -22,7 +21,6 @@ public async ValueTask<Vector> GetEmbeddingAsync(string text, CancellationToken
Stopwatch.GetElapsedTime(timestamp).TotalSeconds, text);
}


return new(embedding);
}

Expand All @@ -41,7 +39,6 @@ public async ValueTask<IReadOnlyList<Vector>> GetEmbeddingsAsync(List<string> te
Stopwatch.GetElapsedTime(timestamp).TotalSeconds);
}


return results;
}
}
Loading

0 comments on commit 12b9dc4

Please sign in to comment.