Skip to content
This repository was archived by the owner on May 25, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all 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
231 changes: 231 additions & 0 deletions docs/adr/ADR002_DbContext_Composition.md

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions docs/adr/ADR002_DbContext_Composition.mmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
flowchart LR
subgraph Shared
C1["DocumentConfiguration"]
C2["ProcessedMessageConfiguration"]
C3["OutboxConfiguration"]
C4["WorkflowCheckpointConfiguration"]
C5["AgentDefinitionConfiguration"]
end

subgraph ApiGateway
A["GatewayDbContext"]
A1["DbSet<Document>"]
A2["DbSet<ProcessedMessage>"]
A3["DbSet<Outbox>"]
A --> C1
A --> C2
A --> C3
end

subgraph Worker
B["WorkerDbContext"]
B1["DbSet<Document>"]
B2["DbSet<ProcessedMessage>"]
B4["DbSet<WorkflowCheckpoint>"]
B5["DbSet<AgentDefinition>"]
B --> C1
B --> C2
B --> C4
B --> C5
end
23 changes: 4 additions & 19 deletions src/ApiGateway/BackgroundServices/OutboxPublisher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,6 @@

namespace ApiGateway.BackgroundServices;

/// <summary>
/// Background service that implements the Transactional Outbox pattern.
/// Polls the outbox table every 5s, publishes pending messages to RabbitMQ via MassTransit,
/// then marks them as processed. This guarantees at-least-once delivery without
/// relying on a distributed transaction between the database and message broker.
///
/// Workflow:
/// 1. POST /upload → document + outbox row saved in same DB transaction
/// 2. OutboxPublisher picks up unprocessed rows (processed_at IS NULL)
/// 3. Deserializes JSON payload → publishes to RabbitMQ
/// 4. Marks row as processed → won't be picked up again
/// </summary>
public class OutboxPublisher : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
Expand All @@ -39,14 +27,13 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
try
{
using var scope = _scopeFactory.CreateScope();
var repository = scope.ServiceProvider.GetRequiredService<IDocumentRepository>();
var pendingMessages = await repository.GetOutboxPendingAsync(stoppingToken);
var outboxRepository = scope.ServiceProvider.GetRequiredService<IOutboxRepository>();
var pendingMessages = await outboxRepository.GetOutboxPendingAsync(stoppingToken);

foreach (var message in pendingMessages)
{
try
{
// Deserialize payload — handle corrupt messages gracefully to avoid blocking the queue
PdfProcessingCommand? command = null;
try
{
Expand All @@ -55,7 +42,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
catch (JsonException ex)
{
_logger.LogError(ex, "Corrupt outbox message payload for {OutboxId}, marking as processed to unblock queue", message.Id);
await repository.MarkOutboxProcessedAsync(message.Id, stoppingToken);
await outboxRepository.MarkOutboxProcessedAsync(message.Id, stoppingToken);
continue;
}

Expand All @@ -65,8 +52,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
_logger.LogInformation("Published outbox message {OutboxId} for document {DocumentId}", message.Id, message.DocumentId);
}

// Mark as processed so it won't be picked up again
await repository.MarkOutboxProcessedAsync(message.Id, stoppingToken);
await outboxRepository.MarkOutboxProcessedAsync(message.Id, stoppingToken);
}
catch (Exception ex)
{
Expand All @@ -79,7 +65,6 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
_logger.LogError(ex, "Error in OutboxPublisher loop");
}

// Poll interval — balance between latency (shorter) and DB load (longer)
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}

Expand Down
48 changes: 0 additions & 48 deletions src/ApiGateway/Data/AppDbContext.cs

This file was deleted.

107 changes: 0 additions & 107 deletions src/ApiGateway/Data/DocumentRepository.cs

This file was deleted.

25 changes: 25 additions & 0 deletions src/ApiGateway/Data/GatewayDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore;
using Shared.Configurations;
using Shared.Models;

namespace ApiGateway.Data;

/// <summary>
/// ApiGateway-specific DbContext with Outbox support.
/// Applies shared entity configurations and defines DbSets for this service.
/// </summary>
public class GatewayDbContext : DbContext
{
public GatewayDbContext(DbContextOptions<GatewayDbContext> options) : base(options) { }

public DbSet<DocumentDto> Documents => Set<DocumentDto>();
public DbSet<ProcessedMessage> ProcessedMessages => Set<ProcessedMessage>();
public DbSet<OutboxMessage> OutboxMessages => Set<OutboxMessage>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new DocumentConfiguration());
modelBuilder.ApplyConfiguration(new ProcessedMessageConfiguration());
modelBuilder.ApplyConfiguration(new OutboxConfiguration());
}
}
25 changes: 7 additions & 18 deletions src/ApiGateway/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using ApiGateway.Data;
using ApiGateway.Repositories;
using ApiGateway.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
Expand All @@ -8,16 +9,6 @@ namespace ApiGateway.Extensions;

public static class ServiceCollectionExtensions
{
/// <summary>
/// Configures the database provider based on environment and connection string availability.
///
/// - Testing environment → in-memory database (for unit tests)
/// - Production with connection string → PostgreSQL with snake_case naming
/// - Fallback (e.g., local dev without PostgreSQL) → in-memory database
///
/// Extracted from Program.cs to comply with SRP — the entry point should
/// only compose services, not decide which database to use.
/// </summary>
public static IServiceCollection AddDatabase(
this IServiceCollection services,
IConfiguration configuration,
Expand All @@ -27,18 +18,18 @@ public static IServiceCollection AddDatabase(

if (environment.IsEnvironment("Testing"))
{
services.AddDbContext<AppDbContext>(options =>
services.AddDbContext<GatewayDbContext>(options =>
options.UseInMemoryDatabase("TestDb"));
}
else if (!string.IsNullOrWhiteSpace(connectionString))
{
services.AddDbContext<AppDbContext>(options =>
services.AddDbContext<GatewayDbContext>(options =>
options.UseNpgsql(connectionString)
.UseSnakeCaseNamingConvention());
}
else
{
services.AddDbContext<AppDbContext>(options =>
services.AddDbContext<GatewayDbContext>(options =>
options.UseInMemoryDatabase("TestDb"));
}

Expand All @@ -49,10 +40,6 @@ public static IServiceCollection AddApplicationServices(this IServiceCollection
{
var storageProvider = configuration.GetValue<string>("Storage__Provider") ?? "local";

// Determine storage path:
// 1. Explicit config via Storage__LocalPath or Storage:LocalPath
// 2. /app/storage if running in Docker (directory exists or explicitly configured)
// 3. Fallback to temp directory for local dev and tests
var localPath = configuration.GetValue<string>("Storage__LocalPath")
?? configuration.GetValue<string>("Storage:LocalPath");

Expand All @@ -71,7 +58,9 @@ public static IServiceCollection AddApplicationServices(this IServiceCollection
});
}

services.AddScoped<IDocumentRepository, DocumentRepository>();
services.AddScoped<ApiGateway.Repositories.DocumentRepository>();
services.AddScoped<IDocumentRepository>(sp => sp.GetRequiredService<ApiGateway.Repositories.DocumentRepository>());
services.AddScoped<IOutboxRepository>(sp => sp.GetRequiredService<ApiGateway.Repositories.DocumentRepository>());

return services;
}
Expand Down
Loading
Loading