Skip to content
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
7 changes: 4 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co

## Project state

WebhookInbox is an ASP.NET Core minimal API project on .NET 10 (`net10.0`, nullable and implicit usings on). The HTTP API lives in `WebhookInbox/Api/` and `Program.cs` only wires DI, the exception handler and `app.MapInboxEndpoints()`; the sample `/weatherforecast` endpoint no longer exists. The domain model of the inbox exists in `WebhookInbox/Domain/` (`InboxEvent` with its lifecycle `Received → Processing → Processed/Failed`, its enums and `InvalidEventTransitionException`), covered by xUnit tests in `WebhookInbox.Tests/`. The persistence infrastructure lives in `WebhookInbox/Infrastructure/`: `AppDbContext` (EF Core on PostgreSQL, snake_case naming via `EFCore.NamingConventions`), the Fluent configuration of `InboxEvent` (table `inbox_events`, unique index on `event_id`, `xmin` as concurrency token) and the `InitialCreate` migration. `AppDbContext` is registered in `Program.cs` with `AddDbContext`. The use cases live in `WebhookInbox/Application/`: `InboxEventService` (register, process, get by `EventId`, list with paging), which depends on the `IInboxEventRepository` port (also in `Application/`), implemented by `EfInboxEventRepository` in `Infrastructure/`. `RegisterAsync` returns `RegisterResult(Event, Created)`: a duplicate `EventId` is not an exception outside the service. `Program.cs` registers `TimeProvider`, the repository, the processor (`NoOpInboxEventProcessor` for now) and the service in DI. The inbox endpoints are `POST /webhooks/{source}` (raw body, `X-Event-Id` and `X-Event-Type` headers, `202` for new and `200` for a duplicate `EventId`, decided from `RegisterResult.Created` without `try/catch`), `GET /inbox/events/{eventId}`, `GET /inbox/events?status=&page=&pageSize=` and `POST /inbox/events/{eventId}/process`. There is no authentication or signature verification yet, and the EF repository has not been exercised against a real PostgreSQL.
WebhookInbox is an ASP.NET Core minimal API project on .NET 10 (`net10.0`, nullable and implicit usings on). The HTTP API lives in `WebhookInbox/Api/` and `Program.cs` only wires DI, the exception handler and `app.MapInboxEndpoints()`; the sample `/weatherforecast` endpoint no longer exists. The domain model of the inbox exists in `WebhookInbox/Domain/` (`InboxEvent` with its lifecycle `Received → Processing → Processed/Failed`, plus `Processing → Failed` by timeout through `MarkTimedOut`, its enums, `InvalidEventTransitionException` and `ProcessingNotTimedOutException`), covered by xUnit tests in `WebhookInbox.Tests/`. The persistence infrastructure lives in `WebhookInbox/Infrastructure/`: `AppDbContext` (EF Core on PostgreSQL, snake_case naming via `EFCore.NamingConventions`), the Fluent configuration of `InboxEvent` (table `inbox_events`, unique index on `event_id`, `xmin` as concurrency token) and the `InitialCreate` and `AddProcessingStartedAt` migrations. `AppDbContext` is registered in `Program.cs` with `AddDbContext`. The use cases live in `WebhookInbox/Application/`: `InboxEventService` (register, process, recover, get by `EventId`, list with paging), which depends on the `IInboxEventRepository` port (also in `Application/`), implemented by `EfInboxEventRepository` in `Infrastructure/`. `RegisterAsync` returns `RegisterResult(Event, Created)`: a duplicate `EventId` is not an exception outside the service. `Program.cs` registers `TimeProvider`, the repository, the processor (`NoOpInboxEventProcessor` for now) and the service in DI. The inbox endpoints are `POST /webhooks/{source}` (raw body, `X-Event-Id` and `X-Event-Type` headers, `202` for new and `200` for a duplicate `EventId`, decided from `RegisterResult.Created` without `try/catch`), `GET /inbox/events/{eventId}`, `GET /inbox/events?status=&page=&pageSize=` `POST /inbox/events/{eventId}/process` and `POST /inbox/events/{eventId}/recover` (moves an event stuck in `Processing` past the timeout to `Failed` with `LastError` `"Processing timed out"`, so it can be retried with `/process`; there is no background worker, find stuck events with `GET /inbox/events?status=Processing`). There is no authentication or signature verification yet, and the EF repository has not been exercised against a real PostgreSQL.

## Layout

Expand All @@ -17,12 +17,13 @@ WebhookInbox is an ASP.NET Core minimal API project on .NET 10 (`net10.0`, nulla
| --- | --- | --- |
| `EventNotFoundException` | 404 | Warning |
| `InvalidEventTransitionException`, `ConcurrencyConflictException`, `DuplicateEventException` (defensive) | 409 | Warning |
| `ProcessingNotTimedOutException` | 409, title `Processing not timed out` | Warning |
| `ArgumentException` (incl. `ArgumentOutOfRangeException`) | 400 | Warning |
| Anything else | 500, title `An unexpected error occurred`, `detail` only in Development | Error with the exception |

In `4xx`, `detail` is `exception.Message`.
- `WebhookInbox/Domain/`: domain layer, organized by type: `Entities/`, `Enums/` and `Exceptions/` (`DomainException`, `InvalidEventTransitionException`). Only the entity and its lifecycle rules live here. It must not reference `Application/`, `Infrastructure/`, ASP.NET Core or EF Core; time comes in as a parameter.
- `WebhookInbox/Application/`: use-case layer, organized by type: `Services/` (`InboxEventService` with `RegisterAsync`, `ProcessAsync`, `GetByEventIdAsync` and `ListAsync`), `Dtos/` (`InboxEventDto`, `PagedResult<T>`, `RegisterResult`), `Abstractions/` (`IInboxEventProcessor`, `IInboxEventRepository`) and `Exceptions/` (base `ApplicationLayerException` and `DuplicateEventException`, `ConcurrencyConflictException`, `EventNotFoundException`). It references `Domain/` but never `Infrastructure/`, ASP.NET Core or EF Core. Exceptions propagate out of the service except `DuplicateEventException` on register, which becomes `Created = false`; a processor failure is recorded as `Failed` instead of rethrown.
- `WebhookInbox/Domain/`: domain layer, organized by type: `Entities/`, `Enums/` and `Exceptions/` (`DomainException`, `InvalidEventTransitionException`, `ProcessingNotTimedOutException`). `InboxEvent.ProcessingStartedAt` is set by `StartProcessing(startedAt)` and kept after the attempt ends; `MarkTimedOut(now, timeout)` moves `Processing → Failed` once `now - ProcessingStartedAt >= timeout` (a null start counts as expired) and does not change `AttemptCount`. Only the entity and its lifecycle rules live here. It must not reference `Application/`, `Infrastructure/`, ASP.NET Core or EF Core; time comes in as a parameter.
- `WebhookInbox/Application/`: use-case layer, organized by type: `Services/` (`InboxEventService` with `RegisterAsync`, `ProcessAsync`, `RecoverAsync`, `GetByEventIdAsync` and `ListAsync`), `Options/` (`ProcessingRecoveryOptions`, section `Inbox:Recovery`, `ProcessingTimeout` default `00:05:00`, set in `appsettings.json` and validated `> 0` on startup; a real processor must be idempotent, because recovering a slow-but-alive event can lead to a double execution), `Dtos/` (`InboxEventDto`, `PagedResult<T>`, `RegisterResult`), `Abstractions/` (`IInboxEventProcessor`, `IInboxEventRepository`) and `Exceptions/` (base `ApplicationLayerException` and `DuplicateEventException`, `ConcurrencyConflictException`, `EventNotFoundException`). It references `Domain/` but never `Infrastructure/`, ASP.NET Core or EF Core. Exceptions propagate out of the service except `DuplicateEventException` on register, which becomes `Created = false`; a processor failure is recorded as `Failed` instead of rethrown.
- `WebhookInbox/Infrastructure/`: persistence layer. Also holds `EfInboxEventRepository` (implements `IInboxEventRepository`; translates Postgres `23505` to `DuplicateEventException` and `DbUpdateConcurrencyException` to `ConcurrencyConflictException`, both from `Application/Exceptions/`) and `NoOpInboxEventProcessor`, the placeholder `IInboxEventProcessor`. `AppDbContext.cs`, `Configurations/` (one `IEntityTypeConfiguration<T>` per entity, picked up by `ApplyConfigurationsFromAssembly`) and `Migrations/` (generated by `dotnet ef`, do not edit by hand). The connection string is `ConnectionStrings:WebhookInbox` in `appsettings.Development.json`; override it with the `ConnectionStrings__WebhookInbox` env var.
- `WebhookInbox.Tests/`: xUnit test project referencing `WebhookInbox`. Domain tests are in `Domain/`. `InboxEventService` tests are in `Application/`, with an in-memory repository fake and a fake processor. `GlobalExceptionHandler` tests are in `Api/` (`DefaultHttpContext`, no `WebApplicationFactory`).
- Dependency rules: `Domain/` references nothing else. `Application/` references only `Domain/`. `Infrastructure/` references `Application/` and `Domain/`. `Api/` references `Application/` and `Domain/`.
Expand Down
1 change: 1 addition & 0 deletions WebhookInbox.Tests/Api/GlobalExceptionHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ private sealed class FakeHostEnvironment(string environmentName) : IHostEnvironm
{
{ new EventNotFoundException("evt_1"), StatusCodes.Status404NotFound },
{ new InvalidEventTransitionException(EventStatus.Processed, "StartProcessing"), StatusCodes.Status409Conflict },
{ new ProcessingNotTimedOutException(DateTimeOffset.UnixEpoch, TimeSpan.FromMinutes(5)), StatusCodes.Status409Conflict },
{ new ConcurrencyConflictException("evt_1"), StatusCodes.Status409Conflict },
{ new DuplicateEventException("evt_1"), StatusCodes.Status409Conflict },
{ new ArgumentException("bad argument"), StatusCodes.Status400BadRequest },
Expand Down
83 changes: 79 additions & 4 deletions WebhookInbox.Tests/Application/InboxEventServiceTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using Microsoft.Extensions.Options;
using WebhookInbox.Application.Abstractions;
using WebhookInbox.Application.Dtos;
using WebhookInbox.Application.Exceptions;
using WebhookInbox.Application.Options;
using WebhookInbox.Application.Services;
using WebhookInbox.Domain.Entities;
using WebhookInbox.Domain.Enums;
Expand All @@ -16,6 +18,7 @@ private sealed class MutableTimeProvider(DateTimeOffset now) : TimeProvider
public override DateTimeOffset GetUtcNow() => Now;
}

private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(5);
private static readonly DateTimeOffset Start = new(2026, 11, 27, 10, 0, 0, TimeSpan.Zero);

private static (InboxEventService Service, InMemoryInboxEventRepository Repo, MutableTimeProvider Time) Create() =>
Expand All @@ -26,7 +29,8 @@ private static (InboxEventService Service, InMemoryInboxEventRepository Repo, Mu
{
var repo = new InMemoryInboxEventRepository();
var time = new MutableTimeProvider(Start);
var service = new InboxEventService(repo, processor, time);
var service = new InboxEventService(repo, processor, time,
Options.Create(new ProcessingRecoveryOptions { ProcessingTimeout = Timeout }));
return (service, repo, time);
}

Expand Down Expand Up @@ -143,7 +147,7 @@ public async Task ListAsync_WithStatusFilter_ReturnsOnlyThatStatusNewestFirst()
foreach (var id in new[] { "evt_1", "evt_3" })
{
var e = repo.Events.Single(x => x.EventId == id);
e.StartProcessing();
e.StartProcessing(time.GetUtcNow());
e.MarkFailed("boom");
}

Expand Down Expand Up @@ -293,9 +297,9 @@ await Assert.ThrowsAsync<InvalidEventTransitionException>(() =>
public async Task ProcessAsync_AlreadyProcessing_ThrowsInvalidTransitionWithoutCallingProcessor()
{
var processor = new FakeInboxEventProcessor();
var (service, repo, _) = Create(processor);
var (service, repo, time) = Create(processor);
await service.RegisterAsync("evt_1", "stripe", "invoice.paid", "{}", CancellationToken.None);
repo.Events.Single().StartProcessing();
repo.Events.Single().StartProcessing(time.GetUtcNow());

await Assert.ThrowsAsync<InvalidEventTransitionException>(() =>
service.ProcessAsync("evt_1", CancellationToken.None));
Expand Down Expand Up @@ -328,4 +332,75 @@ await Assert.ThrowsAsync<OperationCanceledException>(() =>

Assert.Equal(EventStatus.Processing, repo.Events.Single().Status);
}

// RecoverAsync

[Fact]
public async Task RecoverAsync_Missing_ThrowsEventNotFoundException()
{
var (service, repo, _) = Create();

var ex = await Assert.ThrowsAsync<EventNotFoundException>(() =>
service.RecoverAsync("nope", CancellationToken.None));

Assert.Equal("nope", ex.EventId);
Assert.Equal(0, repo.UpdateCallCount);
}

[Fact]
public async Task RecoverAsync_ExpiredProcessing_MovesToFailedAndUpdatesOnce()
{
var (service, repo, time) = Create();
await service.RegisterAsync("evt_1", "stripe", "invoice.paid", "{}", CancellationToken.None);
repo.Events.Single().StartProcessing(Start);
time.Now = Start + Timeout;

var dto = await service.RecoverAsync("evt_1", CancellationToken.None);

Assert.Equal(EventStatus.Failed, dto.Status);
Assert.Equal("Processing timed out", dto.LastError);
Assert.Equal(1, dto.AttemptCount);
Assert.Equal(Start, dto.ProcessingStartedAt);
Assert.Equal(1, repo.UpdateCallCount);
}

[Fact]
public async Task RecoverAsync_NotExpiredProcessing_ThrowsWithoutUpdate()
{
var (service, repo, time) = Create();
await service.RegisterAsync("evt_1", "stripe", "invoice.paid", "{}", CancellationToken.None);
repo.Events.Single().StartProcessing(Start);
time.Now = Start + Timeout - TimeSpan.FromSeconds(1);

await Assert.ThrowsAsync<ProcessingNotTimedOutException>(() =>
service.RecoverAsync("evt_1", CancellationToken.None));

Assert.Equal(EventStatus.Processing, repo.Events.Single().Status);
Assert.Equal(0, repo.UpdateCallCount);
}

[Fact]
public async Task RecoverAsync_NotProcessing_ThrowsInvalidTransitionWithoutUpdate()
{
var (service, repo, _) = Create();
await service.RegisterAsync("evt_1", "stripe", "invoice.paid", "{}", CancellationToken.None);

await Assert.ThrowsAsync<InvalidEventTransitionException>(() =>
service.RecoverAsync("evt_1", CancellationToken.None));

Assert.Equal(0, repo.UpdateCallCount);
}

[Fact]
public async Task ProcessAsync_SetsProcessingStartedAtFromTimeProvider()
{
var (service, _, time) = Create();
await service.RegisterAsync("evt_1", "stripe", "invoice.paid", "{}", CancellationToken.None);
var startedAt = Start.AddMinutes(3);
time.Now = startedAt;

var dto = await service.ProcessAsync("evt_1", CancellationToken.None);

Assert.Equal(startedAt, dto.ProcessingStartedAt);
}
}
Loading