Skip to content

Commit

Permalink
♻️ Make db calls async (#162)
Browse files Browse the repository at this point in the history
asdf
  • Loading branch information
MattParkerDev authored Mar 15, 2024
1 parent 99a11da commit fe698a7
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 57 deletions.
19 changes: 10 additions & 9 deletions src/Application/Services/ChatHistoryService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Application.Contracts;
using Domain;
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SharedClasses;

Expand Down Expand Up @@ -37,23 +38,23 @@ public ChatHistoryService(
_semanticKernelService = semanticKernelService;
}

public ConversationHistoryModel? GetConversation(int id)
public async Task<ConversationHistoryModel?> GetConversation(int id)
{
return _context.ConversationHistories
.FirstOrDefault(s => s.Id == id && s.User == Email);
return await _context.ConversationHistories
.FirstOrDefaultAsync(s => s.Id == id && s.User == Email);
}

public IEnumerable<ChatHistoryDetail> GetConversations()
public async Task<List<ChatHistoryDetail>> GetConversations()
{
return _context.ConversationHistories
return await _context.ConversationHistories
.Where(s => s.User == Email)
.OrderByDescending(s => s.Date)
.Select(s =>
new ChatHistoryDetail
{
Id = s.Id,
ConversationTitle = s.ConversationTitle
});
}).ToListAsync();
}

public async Task<int> AddConversation(string conversation, string firstMessage)
Expand Down Expand Up @@ -85,7 +86,7 @@ public async Task UpdateConversation(int id, string conversation)
{
ValidateConversation(conversation);

var record = _context.ConversationHistories.FirstOrDefault(s => s.Id == id && s.User == Email);
var record = await _context.ConversationHistories.FirstOrDefaultAsync(s => s.Id == id && s.User == Email);
if (record == null)
throw new ArgumentException("Conversation not found");

Expand All @@ -111,8 +112,8 @@ private static void ValidateConversation(string conversation)
throw new ArgumentException("Conversation is not valid JSON");
}

private Task<string> GetConversationTitle(string firstMessage)
private async Task<string> GetConversationTitle(string firstMessage)
{
return _semanticKernelService.GetConversationTitle(firstMessage);
return await _semanticKernelService.GetConversationTitle(firstMessage);
}
}
8 changes: 4 additions & 4 deletions src/Application/Services/LeaderboardService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Application.Contracts;
using Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace Application.Services;

Expand All @@ -12,13 +13,13 @@ public LeaderboardService(IRulesContext rulesContext)
_rulesContext = rulesContext;
}

public IEnumerable<LeaderboardUser> GetLeaderboardStats()
public async Task<List<LeaderboardUser>> GetLeaderboardStats()
{
//Needs to be universal time in order to work the database date values
var oneMonth = DateTime.Now.AddMonths(-1).ToUniversalTime();
var oneYear = DateTime.Now.AddYears(-1).ToUniversalTime();

return _rulesContext.UserStats
return await _rulesContext.UserStats
.GroupBy(s => new { s.Name, s.Email })
.Select(group => new LeaderboardUser()
{
Expand All @@ -27,7 +28,6 @@ public IEnumerable<LeaderboardUser> GetLeaderboardStats()
LastMonth = group.Count(u => u.Date >= oneMonth),
LastYear = group.Count(u => u.Date >= oneYear),
AllTime = group.Count()
})
.AsEnumerable();
}).ToListAsync();
}
}
38 changes: 38 additions & 0 deletions src/WebAPI/DependencyInjection.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Application.Contracts;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.ApplicationInsights;
using WebAPI.Services;
Expand Down Expand Up @@ -59,6 +60,43 @@ public static IServiceCollection AddWebApi(
.AllowCredentials()
)
);

var signingAuthority = configuration.GetValue<string>("SigningAuthority");

services.AddAuthentication(options =>
{
// Identity made Cookie authentication the default.
// However, we want JWT Bearer Auth to be the default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = signingAuthority;
options.Audience = "rulesgpt";
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };

options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];

// If the request is for our hub...
var path = context.HttpContext.Request.Path;

if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/ruleshub")))
{
// Read the token out of the query string
context.Token = accessToken;
}

return Task.CompletedTask;
}
};
});

services.AddHealthChecks();

return services;
}
Expand Down
39 changes: 2 additions & 37 deletions src/WebAPI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using Azure.Identity;
using Application;
using Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using WebAPI;
using WebAPI.Routes;
using WebAPI.SignalR;
Expand All @@ -11,41 +9,6 @@
const string RulesGptCorsPolicy = nameof(RulesGptCorsPolicy);
const string ChatHistoryPolicy = nameof(ChatHistoryPolicy);

var signingAuthority = builder.Configuration.GetValue<string>("SigningAuthority");

builder.Services.AddAuthentication(options =>
{
// Identity made Cookie authentication the default.
// However, we want JWT Bearer Auth to be the default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = signingAuthority;
options.Audience = "rulesgpt";
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };

options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];

// If the request is for our hub...
var path = context.HttpContext.Request.Path;

if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/ruleshub")))
{
// Read the token out of the query string
context.Token = accessToken;
}

return Task.CompletedTask;
}
};
});

builder.Services.AddAuthorizationBuilder().AddPolicy(ChatHistoryPolicy, policy =>
{
policy.RequireAuthenticatedUser();
Expand Down Expand Up @@ -73,5 +36,7 @@
app.MapConversationRoutes();
app.MapHub<RulesHub>("/ruleshub");

app.UseHealthChecks("/health");

app.Logger.LogInformation("Starting WebAPI");
app.Run();
4 changes: 2 additions & 2 deletions src/WebAPI/Routes/ConversationHistoryRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static void MapConversationRoutes(this WebApplication app)
"/Conversation/{id}",
async (ChatHistoryService historyService, int id) =>
{
var results = historyService.GetConversation(id);
var results = await historyService.GetConversation(id);
return TypedResults.Ok(results);
})
.WithName("GetConversationById")
Expand All @@ -27,7 +27,7 @@ public static void MapConversationRoutes(this WebApplication app)
"/Conversations",
async (ChatHistoryService historyService) =>
{
var results = historyService.GetConversations();
var results = await historyService.GetConversations();
return TypedResults.Ok(results);
})
.WithName("GetConversationsForUser")
Expand Down
5 changes: 2 additions & 3 deletions src/WebAPI/Routes/LeaderboardRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ public static void MapLeaderboardRoutes(this WebApplication app)
routeGroup
.MapGet(
"/getLeaderboardStats",
Ok<IEnumerable<LeaderboardUser>> (HttpContext context) =>
async Task<Ok<List<LeaderboardUser>>> (LeaderboardService leaderboardService) =>
{
var service = context.RequestServices.GetRequiredService<LeaderboardService>();
return TypedResults.Ok(service.GetLeaderboardStats());
return TypedResults.Ok(await leaderboardService.GetLeaderboardStats());
}
)
.WithName("GetLeaderboardStats");
Expand Down
4 changes: 2 additions & 2 deletions src/WebAPI/SignalR/SignalRHubFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ public SignalRHubFilter(ILogger<RulesHub> logger)
_logger = logger;
}

public async ValueTask<object> InvokeMethodAsync(
public async ValueTask<object?> InvokeMethodAsync(
HubInvocationContext invocationContext,
Func<HubInvocationContext, ValueTask<object>> next
Func<HubInvocationContext, ValueTask<object?>> next
)
{
_logger.LogInformation(
Expand Down

0 comments on commit fe698a7

Please sign in to comment.