@@ -0,0 +1,40 @@
|
||||
using Api.Data.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Api.Data;
|
||||
|
||||
public sealed class CvMatcherDbContext : DbContext
|
||||
{
|
||||
public CvMatcherDbContext(DbContextOptions<CvMatcherDbContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<CvMatchResultEntity> CvMatchResults => Set<CvMatchResultEntity>();
|
||||
public DbSet<CvMatcherChatCacheEntity> CvMatcherChatCache => Set<CvMatcherChatCacheEntity>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<CvMatchResultEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("CvMatchResults");
|
||||
entity.HasKey(x => x.Id);
|
||||
entity.Property(x => x.Id).HasMaxLength(64);
|
||||
entity.Property(x => x.CvDocumentId).HasMaxLength(64).IsRequired();
|
||||
entity.Property(x => x.JobDocumentId).HasMaxLength(64).IsRequired();
|
||||
entity.Property(x => x.ResultJson).IsRequired();
|
||||
entity.Property(x => x.CreatedAt).HasDefaultValueSql("SYSUTCDATETIME()");
|
||||
entity.HasIndex(x => new { x.CvDocumentId, x.JobDocumentId }).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<CvMatcherChatCacheEntity>(entity =>
|
||||
{
|
||||
entity.ToTable("CvMatcherChatCache");
|
||||
entity.HasKey(x => x.CacheKey);
|
||||
entity.Property(x => x.CacheKey).HasMaxLength(64);
|
||||
entity.Property(x => x.Model).HasMaxLength(120).IsRequired();
|
||||
entity.Property(x => x.Temperature).HasColumnType("decimal(4,2)");
|
||||
entity.Property(x => x.ResponseText).IsRequired();
|
||||
entity.Property(x => x.CreatedAt).HasDefaultValueSql("SYSUTCDATETIME()");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Api.Data.Entities;
|
||||
|
||||
public sealed class CvMatchResultEntity
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string CvDocumentId { get; set; } = string.Empty;
|
||||
public string JobDocumentId { get; set; } = string.Empty;
|
||||
public string ResultJson { get; set; } = string.Empty;
|
||||
public int Score { get; set; }
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Api.Data.Entities;
|
||||
|
||||
public sealed class CvMatcherChatCacheEntity
|
||||
{
|
||||
public string CacheKey { get; set; } = string.Empty;
|
||||
public string Model { get; set; } = string.Empty;
|
||||
public decimal Temperature { get; set; }
|
||||
public string ResponseText { get; set; } = string.Empty;
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
using Azure.Identity;
|
||||
using Api.Data;
|
||||
using Api.Services;
|
||||
using Api.Services.Contracts;
|
||||
using Api.Settings;
|
||||
using Microsoft.AspNetCore.Diagnostics;
|
||||
using Serilog;
|
||||
using System.Reflection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
DotNetEnv.Env.Load();
|
||||
|
||||
@@ -69,7 +71,10 @@ try
|
||||
builder.Services.AddHttpClient<IRagApiClient, RagApiClient>();
|
||||
builder.Services.AddHttpClient<IMatcherAiClient, MatcherAiClient>();
|
||||
builder.Services.AddHttpClient<IJobTextExtractor, JobTextExtractor>();
|
||||
builder.Services.AddSingleton<IMatcherRepository, SqlMatcherRepository>();
|
||||
builder.Services.AddDbContext<CvMatcherDbContext>(options =>
|
||||
options.UseSqlServer(builder.Configuration.GetConnectionString("CvMatcherDb")
|
||||
?? throw new InvalidOperationException("Connection string 'CvMatcherDb' is missing.")));
|
||||
builder.Services.AddScoped<IMatcherRepository, EfMatcherRepository>();
|
||||
builder.Services.AddScoped<ICvMatcherService, CvMatcherService>();
|
||||
builder.Services.AddSingleton<IEmailService, EmailService>();
|
||||
|
||||
@@ -160,6 +165,14 @@ try
|
||||
app.MapControllers();
|
||||
app.MapGet("/health", () => Results.Ok(new { status = "ok", service = "cv-matcher-api", version = appVersion, timeUtc = DateTimeOffset.UtcNow }));
|
||||
|
||||
|
||||
Log.Information("Running EfCore DbMigrations if any");
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<CvMatcherDbContext>();
|
||||
db.Database.Migrate();
|
||||
}
|
||||
|
||||
Log.Information("{Service} startup complete", "cv-matcher-api");
|
||||
app.Run();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Text.Json;
|
||||
using Api.Data;
|
||||
using Api.Data.Entities;
|
||||
using Api.Responses;
|
||||
using Api.Services.Contracts;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Api.Services;
|
||||
|
||||
public sealed class EfMatcherRepository : IMatcherRepository
|
||||
{
|
||||
private readonly CvMatcherDbContext _db;
|
||||
private readonly ILogger<EfMatcherRepository> _logger;
|
||||
|
||||
public EfMatcherRepository(CvMatcherDbContext db, ILogger<EfMatcherRepository> logger)
|
||||
{
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task InitializeAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Ensuring CV matcher database schema exists using EF Core");
|
||||
await _db.Database.EnsureCreatedAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<JobMatchResponse?> GetMatchAsync(string cvDocumentId, string jobDocumentId, CancellationToken ct)
|
||||
{
|
||||
var json = await _db.CvMatchResults
|
||||
.AsNoTracking()
|
||||
.Where(x => x.CvDocumentId == cvDocumentId && x.JobDocumentId == jobDocumentId)
|
||||
.Select(x => x.ResultJson)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
|
||||
var result = JsonSerializer.Deserialize<JobMatchResponse>(json, new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||
if (result is not null) result.Cached = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task SaveMatchAsync(string cvDocumentId, string jobDocumentId, JobMatchResponse response, CancellationToken ct)
|
||||
{
|
||||
var exists = await _db.CvMatchResults.AnyAsync(
|
||||
x => x.CvDocumentId == cvDocumentId && x.JobDocumentId == jobDocumentId,
|
||||
ct);
|
||||
|
||||
if (exists) return;
|
||||
|
||||
_db.CvMatchResults.Add(new CvMatchResultEntity
|
||||
{
|
||||
Id = Guid.NewGuid().ToString("N"),
|
||||
CvDocumentId = cvDocumentId,
|
||||
JobDocumentId = jobDocumentId,
|
||||
ResultJson = JsonSerializer.Serialize(response, new JsonSerializerOptions(JsonSerializerDefaults.Web)),
|
||||
Score = response.Score,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<string?> GetChatCompletionAsync(string cacheKey, CancellationToken ct)
|
||||
{
|
||||
return await _db.CvMatcherChatCache
|
||||
.AsNoTracking()
|
||||
.Where(x => x.CacheKey == cacheKey)
|
||||
.Select(x => x.ResponseText)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
}
|
||||
|
||||
public async Task SaveChatCompletionAsync(string cacheKey, string model, decimal temperature, string responseText, CancellationToken ct)
|
||||
{
|
||||
var exists = await _db.CvMatcherChatCache.AnyAsync(x => x.CacheKey == cacheKey, ct);
|
||||
if (exists) return;
|
||||
|
||||
_db.CvMatcherChatCache.Add(new CvMatcherChatCacheEntity
|
||||
{
|
||||
CacheKey = cacheKey,
|
||||
Model = model,
|
||||
Temperature = temperature,
|
||||
ResponseText = responseText,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using Api.Responses;
|
||||
using Api.Services.Contracts;
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace Api.Services;
|
||||
|
||||
public sealed class SqlMatcherRepository : IMatcherRepository
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
|
||||
public SqlMatcherRepository(IConfiguration configuration)
|
||||
{
|
||||
_connectionString = configuration.GetConnectionString("CvMatcherDb")
|
||||
?? throw new InvalidOperationException("Connection string 'CvMatcherDb' is missing.");
|
||||
}
|
||||
|
||||
public async Task InitializeAsync(CancellationToken ct)
|
||||
{
|
||||
await EnsureDatabaseExistsAsync(ct);
|
||||
var sql = await File.ReadAllTextAsync(Path.Combine(AppContext.BaseDirectory, "Database", "schema.sql"), ct);
|
||||
await using var connection = new SqlConnection(_connectionString);
|
||||
await connection.OpenAsync(ct);
|
||||
foreach (var commandText in sql.Split("GO", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
await using var command = new SqlCommand(commandText, connection);
|
||||
await command.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<JobMatchResponse?> GetMatchAsync(string cvDocumentId, string jobDocumentId, CancellationToken ct)
|
||||
{
|
||||
const string sql = "SELECT ResultJson FROM CvMatchResults WHERE CvDocumentId = @CvDocumentId AND JobDocumentId = @JobDocumentId";
|
||||
await using var connection = new SqlConnection(_connectionString);
|
||||
await connection.OpenAsync(ct);
|
||||
await using var command = new SqlCommand(sql, connection);
|
||||
command.Parameters.AddWithValue("@CvDocumentId", cvDocumentId);
|
||||
command.Parameters.AddWithValue("@JobDocumentId", jobDocumentId);
|
||||
var json = await command.ExecuteScalarAsync(ct) as string;
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
var result = JsonSerializer.Deserialize<JobMatchResponse>(json, new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||
if (result is not null) result.Cached = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task SaveMatchAsync(string cvDocumentId, string jobDocumentId, JobMatchResponse response, CancellationToken ct)
|
||||
{
|
||||
const string sql = """
|
||||
IF NOT EXISTS (SELECT 1 FROM CvMatchResults WHERE CvDocumentId = @CvDocumentId AND JobDocumentId = @JobDocumentId)
|
||||
INSERT INTO CvMatchResults (Id, CvDocumentId, JobDocumentId, ResultJson, Score, CreatedAt)
|
||||
VALUES (@Id, @CvDocumentId, @JobDocumentId, @ResultJson, @Score, SYSUTCDATETIME())
|
||||
""";
|
||||
await using var connection = new SqlConnection(_connectionString);
|
||||
await connection.OpenAsync(ct);
|
||||
await using var command = new SqlCommand(sql, connection);
|
||||
command.Parameters.AddWithValue("@Id", Guid.NewGuid().ToString("N"));
|
||||
command.Parameters.AddWithValue("@CvDocumentId", cvDocumentId);
|
||||
command.Parameters.AddWithValue("@JobDocumentId", jobDocumentId);
|
||||
command.Parameters.AddWithValue("@ResultJson", JsonSerializer.Serialize(response, new JsonSerializerOptions(JsonSerializerDefaults.Web)));
|
||||
command.Parameters.AddWithValue("@Score", response.Score);
|
||||
await command.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<string?> GetChatCompletionAsync(string cacheKey, CancellationToken ct)
|
||||
{
|
||||
const string sql = "SELECT ResponseText FROM CvMatcherChatCache WHERE CacheKey = @CacheKey";
|
||||
await using var connection = new SqlConnection(_connectionString);
|
||||
await connection.OpenAsync(ct);
|
||||
await using var command = new SqlCommand(sql, connection);
|
||||
command.Parameters.AddWithValue("@CacheKey", cacheKey);
|
||||
return await command.ExecuteScalarAsync(ct) as string;
|
||||
}
|
||||
|
||||
public async Task SaveChatCompletionAsync(string cacheKey, string model, decimal temperature, string responseText, CancellationToken ct)
|
||||
{
|
||||
const string sql = """
|
||||
IF NOT EXISTS (SELECT 1 FROM CvMatcherChatCache WHERE CacheKey = @CacheKey)
|
||||
INSERT INTO CvMatcherChatCache (CacheKey, Model, Temperature, ResponseText, CreatedAt)
|
||||
VALUES (@CacheKey, @Model, @Temperature, @ResponseText, SYSUTCDATETIME())
|
||||
""";
|
||||
await using var connection = new SqlConnection(_connectionString);
|
||||
await connection.OpenAsync(ct);
|
||||
await using var command = new SqlCommand(sql, connection);
|
||||
command.Parameters.AddWithValue("@CacheKey", cacheKey);
|
||||
command.Parameters.AddWithValue("@Model", model);
|
||||
command.Parameters.AddWithValue("@Temperature", temperature);
|
||||
command.Parameters.AddWithValue("@ResponseText", responseText);
|
||||
await command.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
private async Task EnsureDatabaseExistsAsync(CancellationToken ct)
|
||||
{
|
||||
var builder = new SqlConnectionStringBuilder(_connectionString);
|
||||
var databaseName = builder.InitialCatalog;
|
||||
if (string.IsNullOrWhiteSpace(databaseName)) return;
|
||||
|
||||
builder.InitialCatalog = "master";
|
||||
await using var connection = new SqlConnection(builder.ConnectionString);
|
||||
await connection.OpenAsync(ct);
|
||||
var safeName = databaseName.Replace("]", "]]" );
|
||||
await using var command = new SqlCommand($"IF DB_ID(@DatabaseName) IS NULL EXEC('CREATE DATABASE [{safeName}]')", connection);
|
||||
command.Parameters.AddWithValue("@DatabaseName", databaseName);
|
||||
await command.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -11,8 +11,12 @@
|
||||
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.5.1" />
|
||||
<PackageReference Include="Azure.Identity" Version="1.21.0" />
|
||||
<PackageReference Include="DotNetEnv" Version="3.2.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="MailKit" Version="4.16.0" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.1.3" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
|
||||
Reference in New Issue
Block a user