diff --git a/CLAUDE.md b/CLAUDE.md index 83456c9..0eb70a9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 @@ -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`, `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`, `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` 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/`. diff --git a/WebhookInbox.Tests/Api/GlobalExceptionHandlerTests.cs b/WebhookInbox.Tests/Api/GlobalExceptionHandlerTests.cs index bb28512..21e436f 100644 --- a/WebhookInbox.Tests/Api/GlobalExceptionHandlerTests.cs +++ b/WebhookInbox.Tests/Api/GlobalExceptionHandlerTests.cs @@ -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 }, diff --git a/WebhookInbox.Tests/Application/InboxEventServiceTests.cs b/WebhookInbox.Tests/Application/InboxEventServiceTests.cs index 8504386..21304d6 100644 --- a/WebhookInbox.Tests/Application/InboxEventServiceTests.cs +++ b/WebhookInbox.Tests/Application/InboxEventServiceTests.cs @@ -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; @@ -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() => @@ -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); } @@ -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"); } @@ -293,9 +297,9 @@ await Assert.ThrowsAsync(() => 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(() => service.ProcessAsync("evt_1", CancellationToken.None)); @@ -328,4 +332,75 @@ await Assert.ThrowsAsync(() => 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(() => + 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(() => + 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(() => + 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); + } } diff --git a/WebhookInbox.Tests/Domain/InboxEventTests.cs b/WebhookInbox.Tests/Domain/InboxEventTests.cs index 9d45763..200279c 100644 --- a/WebhookInbox.Tests/Domain/InboxEventTests.cs +++ b/WebhookInbox.Tests/Domain/InboxEventTests.cs @@ -69,7 +69,7 @@ public void Receive_NullPayload_Throws() => private static InboxEvent Processing() { var e = NewEvent(); - e.StartProcessing(); + e.StartProcessing(Now); return e; } @@ -94,7 +94,7 @@ public void StartProcessing_FromReceived_MovesToProcessingAndIncrementsAttempt() { var e = NewEvent(); - e.StartProcessing(); + e.StartProcessing(Now); Assert.Equal(EventStatus.Processing, e.Status); Assert.Equal(1, e.AttemptCount); @@ -106,17 +106,60 @@ public void StartProcessing_FromFailed_RetriesAndIncrementsAttempt() var e = Failed(); Assert.Equal(1, e.AttemptCount); - e.StartProcessing(); + e.StartProcessing(Now); Assert.Equal(EventStatus.Processing, e.Status); Assert.Equal(2, e.AttemptCount); } + [Fact] + public void StartProcessing_SetsProcessingStartedAt() + { + var e = NewEvent(); + Assert.Null(e.ProcessingStartedAt); + var at = Now.AddMinutes(1); + + e.StartProcessing(at); + + Assert.Equal(at, e.ProcessingStartedAt); + } + + [Fact] + public void StartProcessing_OnRetry_OverwritesProcessingStartedAt() + { + var e = Failed(); + var retryAt = Now.AddMinutes(10); + + e.StartProcessing(retryAt); + + Assert.Equal(retryAt, e.ProcessingStartedAt); + } + + [Fact] + public void ProcessingStartedAt_IsKeptAfterMarkProcessed() + { + var e = Processing(); + + e.MarkProcessed(Now.AddMinutes(1)); + + Assert.Equal(Now, e.ProcessingStartedAt); + } + + [Fact] + public void ProcessingStartedAt_IsKeptAfterMarkFailed() + { + var e = Processing(); + + e.MarkFailed("boom"); + + Assert.Equal(Now, e.ProcessingStartedAt); + } + [Fact] public void MarkProcessed_FromProcessing_SetsProcessedAndClearsError() { var e = Failed(); - e.StartProcessing(); + e.StartProcessing(Now); var at = Now.AddMinutes(5); e.MarkProcessed(at); @@ -144,7 +187,7 @@ public void StartProcessing_FromProcessed_Throws() { var e = Processed(); - var ex = Assert.Throws(() => e.StartProcessing()); + var ex = Assert.Throws(() => e.StartProcessing(Now)); Assert.Equal(EventStatus.Processed, ex.CurrentStatus); Assert.Equal(EventStatus.Processed, e.Status); @@ -153,7 +196,7 @@ public void StartProcessing_FromProcessed_Throws() [Fact] public void StartProcessing_FromProcessing_Throws() => - Assert.Throws(() => Processing().StartProcessing()); + Assert.Throws(() => Processing().StartProcessing(Now)); [Fact] public void MarkProcessed_FromReceived_Throws() => @@ -184,4 +227,89 @@ public void MarkFailed_FromProcessed_Throws() => [InlineData("")] public void MarkFailed_InvalidError_Throws(string? error) => Assert.ThrowsAny(() => Processing().MarkFailed(error!)); + + // MarkTimedOut + + private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(5); + + // Rebuilds the pre-migration state: Processing with a null ProcessingStartedAt. + private static InboxEvent ProcessingWithoutStart() + { + var e = Processing(); + typeof(InboxEvent).GetProperty(nameof(InboxEvent.ProcessingStartedAt))!.SetValue(e, null); + return e; + } + + [Fact] + public void MarkTimedOut_Expired_MovesToFailedKeepingAttemptCount() + { + var e = Processing(); + + e.MarkTimedOut(Now + Timeout + TimeSpan.FromSeconds(1), Timeout); + + Assert.Equal(EventStatus.Failed, e.Status); + Assert.Equal("Processing timed out", e.LastError); + Assert.Equal(1, e.AttemptCount); + Assert.Equal(Now, e.ProcessingStartedAt); + } + + [Fact] + public void MarkTimedOut_ExactlyAtTimeout_MovesToFailed() + { + var e = Processing(); + + e.MarkTimedOut(Now + Timeout, Timeout); + + Assert.Equal(EventStatus.Failed, e.Status); + } + + [Fact] + public void MarkTimedOut_NotExpired_Throws() + { + var e = Processing(); + + Assert.Throws(() => + e.MarkTimedOut(Now + Timeout - TimeSpan.FromSeconds(1), Timeout)); + + Assert.Equal(EventStatus.Processing, e.Status); + Assert.Null(e.LastError); + } + + [Fact] + public void MarkTimedOut_NullProcessingStartedAt_MovesToFailed() + { + var e = ProcessingWithoutStart(); + Assert.Null(e.ProcessingStartedAt); + + e.MarkTimedOut(Now, Timeout); + + Assert.Equal(EventStatus.Failed, e.Status); + Assert.Equal("Processing timed out", e.LastError); + } + + [Fact] + public void MarkTimedOut_FromReceived_Throws() => + Assert.Throws(() => NewEvent().MarkTimedOut(Now + Timeout, Timeout)); + + [Fact] + public void MarkTimedOut_FromProcessed_Throws() => + Assert.Throws(() => Processed().MarkTimedOut(Now + Timeout, Timeout)); + + [Fact] + public void MarkTimedOut_FromFailed_Throws() => + Assert.Throws(() => Failed().MarkTimedOut(Now + Timeout, Timeout)); + + [Fact] + public void StartProcessing_AfterMarkTimedOut_IsAllowed() + { + var e = Processing(); + e.MarkTimedOut(Now + Timeout, Timeout); + var retryAt = Now + Timeout + TimeSpan.FromMinutes(1); + + e.StartProcessing(retryAt); + + Assert.Equal(EventStatus.Processing, e.Status); + Assert.Equal(2, e.AttemptCount); + Assert.Equal(retryAt, e.ProcessingStartedAt); + } } diff --git a/WebhookInbox/Api/GlobalExceptionHandler.cs b/WebhookInbox/Api/GlobalExceptionHandler.cs index 67fcd5c..13666d5 100644 --- a/WebhookInbox/Api/GlobalExceptionHandler.cs +++ b/WebhookInbox/Api/GlobalExceptionHandler.cs @@ -19,6 +19,7 @@ public async ValueTask TryHandleAsync( { EventNotFoundException => (StatusCodes.Status404NotFound, "Event not found"), InvalidEventTransitionException => (StatusCodes.Status409Conflict, "Invalid event transition"), + ProcessingNotTimedOutException => (StatusCodes.Status409Conflict, "Processing not timed out"), ConcurrencyConflictException => (StatusCodes.Status409Conflict, "Concurrency conflict"), DuplicateEventException => (StatusCodes.Status409Conflict, "Duplicate event"), ArgumentException => (StatusCodes.Status400BadRequest, "Invalid request"), diff --git a/WebhookInbox/Api/InboxEndpoints.cs b/WebhookInbox/Api/InboxEndpoints.cs index 7a8c234..72638e6 100644 --- a/WebhookInbox/Api/InboxEndpoints.cs +++ b/WebhookInbox/Api/InboxEndpoints.cs @@ -83,6 +83,10 @@ public static IEndpointRouteBuilder MapInboxEndpoints(this IEndpointRouteBuilder events.MapPost("/{eventId}/process", async (string eventId, InboxEventService service, CancellationToken ct) => TypedResults.Ok(await service.ProcessAsync(eventId, ct))); + // Moves an event stuck in Processing past the configured timeout to Failed so it can be retried. + events.MapPost("/{eventId}/recover", async (string eventId, InboxEventService service, CancellationToken ct) => + TypedResults.Ok(await service.RecoverAsync(eventId, ct))); + events.MapGet("/{eventId}", async (string eventId, InboxEventService service, CancellationToken ct) => TypedResults.Ok(await service.GetByEventIdAsync(eventId, ct))); diff --git a/WebhookInbox/Application/Dtos/InboxEventDto.cs b/WebhookInbox/Application/Dtos/InboxEventDto.cs index c3e4721..8ffcc3e 100644 --- a/WebhookInbox/Application/Dtos/InboxEventDto.cs +++ b/WebhookInbox/Application/Dtos/InboxEventDto.cs @@ -13,7 +13,8 @@ public sealed record InboxEventDto( DateTimeOffset ReceivedAt, DateTimeOffset? ProcessedAt, int AttemptCount, - string? LastError) + string? LastError, + DateTimeOffset? ProcessingStartedAt) { public static InboxEventDto From(InboxEvent e) => new( e.Id, @@ -25,5 +26,6 @@ public sealed record InboxEventDto( e.ReceivedAt, e.ProcessedAt, e.AttemptCount, - e.LastError); + e.LastError, + e.ProcessingStartedAt); } diff --git a/WebhookInbox/Application/Options/ProcessingRecoveryOptions.cs b/WebhookInbox/Application/Options/ProcessingRecoveryOptions.cs new file mode 100644 index 0000000..69c5970 --- /dev/null +++ b/WebhookInbox/Application/Options/ProcessingRecoveryOptions.cs @@ -0,0 +1,8 @@ +namespace WebhookInbox.Application.Options; + +public sealed class ProcessingRecoveryOptions +{ + public const string SectionName = "Inbox:Recovery"; + + public TimeSpan ProcessingTimeout { get; set; } = TimeSpan.FromMinutes(5); +} diff --git a/WebhookInbox/Application/Services/InboxEventService.cs b/WebhookInbox/Application/Services/InboxEventService.cs index 67cbad5..5f9f0cc 100644 --- a/WebhookInbox/Application/Services/InboxEventService.cs +++ b/WebhookInbox/Application/Services/InboxEventService.cs @@ -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.Domain.Entities; using WebhookInbox.Domain.Enums; @@ -9,7 +11,8 @@ namespace WebhookInbox.Application.Services; public sealed class InboxEventService( IInboxEventRepository repository, IInboxEventProcessor processor, - TimeProvider timeProvider) + TimeProvider timeProvider, + IOptions recoveryOptions) { private const int MaxPageSize = 100; @@ -46,7 +49,7 @@ public async Task ProcessAsync(string eventId, CancellationToken var inboxEvent = await repository.GetByEventIdAsync(eventId, ct) ?? throw new EventNotFoundException(eventId); - inboxEvent.StartProcessing(); + inboxEvent.StartProcessing(timeProvider.GetUtcNow()); await repository.UpdateAsync(inboxEvent, ct); try @@ -66,6 +69,16 @@ public async Task ProcessAsync(string eventId, CancellationToken return InboxEventDto.From(inboxEvent); } + public async Task RecoverAsync(string eventId, CancellationToken ct) + { + var inboxEvent = await repository.GetByEventIdAsync(eventId, ct) + ?? throw new EventNotFoundException(eventId); + + inboxEvent.MarkTimedOut(timeProvider.GetUtcNow(), recoveryOptions.Value.ProcessingTimeout); + await repository.UpdateAsync(inboxEvent, ct); + return InboxEventDto.From(inboxEvent); + } + public async Task GetByEventIdAsync(string eventId, CancellationToken ct) { var inboxEvent = await repository.GetByEventIdAsync(eventId, ct) diff --git a/WebhookInbox/Domain/Entities/InboxEvent.cs b/WebhookInbox/Domain/Entities/InboxEvent.cs index e8d2b16..c04c76d 100644 --- a/WebhookInbox/Domain/Entities/InboxEvent.cs +++ b/WebhookInbox/Domain/Entities/InboxEvent.cs @@ -15,6 +15,7 @@ public sealed class InboxEvent public DateTimeOffset? ProcessedAt { get; private set; } public int AttemptCount { get; private set; } public string? LastError { get; private set; } + public DateTimeOffset? ProcessingStartedAt { get; private set; } private InboxEvent(string eventId, string source, string eventType, string payload, DateTimeOffset receivedAt) { @@ -39,12 +40,13 @@ public static InboxEvent Receive(string eventId, string source, string eventType return new InboxEvent(eventId, source, eventType, payload, receivedAt); } - public void StartProcessing() + public void StartProcessing(DateTimeOffset startedAt) { if (Status is not (EventStatus.Received or EventStatus.Failed)) throw new InvalidEventTransitionException(Status, nameof(StartProcessing)); Status = EventStatus.Processing; + ProcessingStartedAt = startedAt; AttemptCount++; } @@ -58,6 +60,19 @@ public void MarkProcessed(DateTimeOffset processedAt) LastError = null; } + public void MarkTimedOut(DateTimeOffset now, TimeSpan timeout) + { + if (Status != EventStatus.Processing) + throw new InvalidEventTransitionException(Status, nameof(MarkTimedOut)); + + // A null start (rows created before ProcessingStartedAt existed) counts as timed out. + if (ProcessingStartedAt is { } startedAt && now - startedAt < timeout) + throw new ProcessingNotTimedOutException(startedAt, timeout); + + Status = EventStatus.Failed; + LastError = "Processing timed out"; + } + public void MarkFailed(string error) { ArgumentException.ThrowIfNullOrEmpty(error); diff --git a/WebhookInbox/Domain/Exceptions/ProcessingNotTimedOutException.cs b/WebhookInbox/Domain/Exceptions/ProcessingNotTimedOutException.cs new file mode 100644 index 0000000..6845e74 --- /dev/null +++ b/WebhookInbox/Domain/Exceptions/ProcessingNotTimedOutException.cs @@ -0,0 +1,4 @@ +namespace WebhookInbox.Domain.Exceptions; + +public sealed class ProcessingNotTimedOutException(DateTimeOffset processingStartedAt, TimeSpan timeout) + : DomainException($"Event has been processing since '{processingStartedAt:O}' and has not exceeded the timeout of '{timeout}'."); diff --git a/WebhookInbox/Infrastructure/Migrations/20261130021628_AddProcessingStartedAt.Designer.cs b/WebhookInbox/Infrastructure/Migrations/20261130021628_AddProcessingStartedAt.Designer.cs new file mode 100644 index 0000000..4577a79 --- /dev/null +++ b/WebhookInbox/Infrastructure/Migrations/20261130021628_AddProcessingStartedAt.Designer.cs @@ -0,0 +1,99 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using WebhookInbox.Infrastructure; + +#nullable disable + +namespace WebhookInbox.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261130021628_AddProcessingStartedAt")] + partial class AddProcessingStartedAt + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.15") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("WebhookInbox.Domain.Entities.InboxEvent", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AttemptCount") + .HasColumnType("integer") + .HasColumnName("attempt_count"); + + b.Property("EventId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("event_id"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("event_type"); + + b.Property("LastError") + .HasColumnType("text") + .HasColumnName("last_error"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("text") + .HasColumnName("payload"); + + b.Property("ProcessedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("processed_at"); + + b.Property("ProcessingStartedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("processing_started_at"); + + b.Property("ReceivedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("received_at"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("source"); + + b.Property("Status") + .HasColumnType("integer") + .HasColumnName("status"); + + b.Property("xmin") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id") + .HasName("pk_inbox_events"); + + b.HasIndex("EventId") + .IsUnique() + .HasDatabaseName("ix_inbox_events_event_id"); + + b.ToTable("inbox_events", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/WebhookInbox/Infrastructure/Migrations/20261130021628_AddProcessingStartedAt.cs b/WebhookInbox/Infrastructure/Migrations/20261130021628_AddProcessingStartedAt.cs new file mode 100644 index 0000000..b33839b --- /dev/null +++ b/WebhookInbox/Infrastructure/Migrations/20261130021628_AddProcessingStartedAt.cs @@ -0,0 +1,29 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace WebhookInbox.Infrastructure.Migrations +{ + /// + public partial class AddProcessingStartedAt : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "processing_started_at", + table: "inbox_events", + type: "timestamp with time zone", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "processing_started_at", + table: "inbox_events"); + } + } +} diff --git a/WebhookInbox/Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/WebhookInbox/Infrastructure/Migrations/AppDbContextModelSnapshot.cs index d679623..22cc72d 100644 --- a/WebhookInbox/Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/WebhookInbox/Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -57,6 +57,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("timestamp with time zone") .HasColumnName("processed_at"); + b.Property("ProcessingStartedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("processing_started_at"); + b.Property("ReceivedAt") .HasColumnType("timestamp with time zone") .HasColumnName("received_at"); diff --git a/WebhookInbox/Program.cs b/WebhookInbox/Program.cs index 961ff3b..ca9facf 100644 --- a/WebhookInbox/Program.cs +++ b/WebhookInbox/Program.cs @@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore; using WebhookInbox.Api; using WebhookInbox.Application.Abstractions; +using WebhookInbox.Application.Options; using WebhookInbox.Application.Services; using WebhookInbox.Infrastructure; @@ -17,6 +18,10 @@ builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddOptions() + .BindConfiguration(ProcessingRecoveryOptions.SectionName) + .Validate(o => o.ProcessingTimeout > TimeSpan.Zero, "Inbox:Recovery:ProcessingTimeout must be greater than zero.") + .ValidateOnStart(); builder.Services.AddScoped(); builder.Services.AddProblemDetails(); diff --git a/WebhookInbox/WebhookInbox.http b/WebhookInbox/WebhookInbox.http index f03bacc..5f990d9 100644 --- a/WebhookInbox/WebhookInbox.http +++ b/WebhookInbox/WebhookInbox.http @@ -103,4 +103,20 @@ POST {{WebhookInbox_HostAddress}}/inbox/events/evt-1/process ### Unknown event -> 404 ProblemDetails POST {{WebhookInbox_HostAddress}}/inbox/events/no-existe/process +### --------------------------------------------------------------- +### POST /inbox/events/{eventId}/recover: move a stuck Processing event to Failed +### --------------------------------------------------------------- + +### Processing for longer than Inbox:Recovery:ProcessingTimeout (default 5 min) -> 200, status "Failed", lastError "Processing timed out" +### To get one: UPDATE inbox_events SET status = 1, processing_started_at = now() - interval '10 minutes' WHERE event_id = 'evt-1'; +### After this, POST /inbox/events/evt-1/process retries it. +POST {{WebhookInbox_HostAddress}}/inbox/events/evt-1/recover + +### Processing but timeout not exceeded, or not in Processing (e.g. Processed) -> 409 ProblemDetails +### To get a non-expired one: UPDATE inbox_events SET status = 1, processing_started_at = now() WHERE event_id = 'evt-1'; +POST {{WebhookInbox_HostAddress}}/inbox/events/evt-1/recover + +### Unknown event -> 404 ProblemDetails +POST {{WebhookInbox_HostAddress}}/inbox/events/no-existe/recover + ### diff --git a/WebhookInbox/appsettings.json b/WebhookInbox/appsettings.json index 10f68b8..feadb3c 100644 --- a/WebhookInbox/appsettings.json +++ b/WebhookInbox/appsettings.json @@ -5,5 +5,10 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "Inbox": { + "Recovery": { + "ProcessingTimeout": "00:05:00" + } + } } diff --git a/specs/07-recuperacion-eventos-atascados.md b/specs/07-recuperacion-eventos-atascados.md index b0f7578..419da68 100644 --- a/specs/07-recuperacion-eventos-atascados.md +++ b/specs/07-recuperacion-eventos-atascados.md @@ -1,6 +1,6 @@ # SPEC 07 — Recuperación de eventos atascados en Processing -> **Estado:** aprobado +> **Estado:** implementado > **Depende de:** SPEC 02, SPEC 03, SPEC 04, SPEC 05, SPEC 06 > **Fecha:** 2026-11-29 > **Objetivo:** Permitir pasar a `Failed`, mediante un endpoint manual, un evento que lleva en `Processing` más tiempo que un timeout configurable, para que pueda reintentarse con `/process`. @@ -121,29 +121,29 @@ Convenciones: ## Criterios de aceptación -- [ ] `dotnet build WebhookInbox.slnx` compila sin errores ni warnings nuevos. -- [ ] `dotnet test` pasa todos los tests. -- [ ] Existe `WebhookInbox/Domain/Exceptions/ProcessingNotTimedOutException.cs` y hereda de `DomainException`. -- [ ] Existe `WebhookInbox/Application/Options/ProcessingRecoveryOptions.cs`. -- [ ] Existe exactamente una migración nueva, `AddProcessingStartedAt`, en `Infrastructure/Migrations/`, y solo añade la columna nullable `processing_started_at`. -- [ ] `EventStatus` sigue teniendo los mismos cuatro valores en el mismo orden. -- [ ] Ningún archivo de `WebhookInbox/Application/` tiene `using` de `Microsoft.AspNetCore`, `Microsoft.EntityFrameworkCore` ni `WebhookInbox.Infrastructure`. -- [ ] Un test verifica que `MarkTimedOut` sobre un `Processing` vencido deja `Failed`, `LastError` `"Processing timed out"` y el mismo `AttemptCount`. -- [ ] Un test verifica que `MarkTimedOut` sobre un `Processing` no vencido lanza `ProcessingNotTimedOutException`. -- [ ] Un test verifica que `MarkTimedOut` con `ProcessingStartedAt` null recupera el evento. -- [ ] Un test verifica que `MarkTimedOut` fuera de `Processing` lanza `InvalidEventTransitionException`. -- [ ] `GlobalExceptionHandlerTests` cubre `ProcessingNotTimedOutException` → `409`. -- [ ] `appsettings.json` contiene `Inbox:Recovery:ProcessingTimeout` con `"00:05:00"`. -- [ ] Con `ProcessingTimeout` a `"00:00:00"` la API no arranca (falla `ValidateOnStart`). -- [ ] Con Postgres levantado, `POST /inbox/events/evt-1/process` devuelve un DTO con `processingStartedAt` no nulo. -- [ ] Con un evento puesto en `Processing` a mano (`UPDATE inbox_events SET status = 1, processing_started_at = now() - interval '10 minutes'`), `POST /inbox/events/{eventId}/recover` devuelve `200` con `status` `"Failed"` y `lastError` `"Processing timed out"`. -- [ ] Tras eso, `POST /inbox/events/{eventId}/process` devuelve `200` con `status` `"Processed"` y `attemptCount` incrementado. -- [ ] Con `processing_started_at = now()` en `Processing`, `/recover` devuelve `409` ProblemDetails. -- [ ] `/recover` sobre un evento `Processed` devuelve `409`. -- [ ] `POST /inbox/events/no-existe/recover` devuelve `404`. -- [ ] Los endpoints existentes devuelven los mismos códigos que en SPEC 05. -- [ ] `WebhookInbox.http` contiene ejemplos de `/recover`. -- [ ] `CLAUDE.md` documenta `/recover`, `ProcessingStartedAt`, `ProcessingRecoveryOptions` y la fila nueva del handler. +- [x] `dotnet build WebhookInbox.slnx` compila sin errores ni warnings nuevos. +- [x] `dotnet test` pasa todos los tests. +- [x] Existe `WebhookInbox/Domain/Exceptions/ProcessingNotTimedOutException.cs` y hereda de `DomainException`. +- [x] Existe `WebhookInbox/Application/Options/ProcessingRecoveryOptions.cs`. +- [x] Existe exactamente una migración nueva, `AddProcessingStartedAt`, en `Infrastructure/Migrations/`, y solo añade la columna nullable `processing_started_at`. +- [x] `EventStatus` sigue teniendo los mismos cuatro valores en el mismo orden. +- [x] Ningún archivo de `WebhookInbox/Application/` tiene `using` de `Microsoft.AspNetCore`, `Microsoft.EntityFrameworkCore` ni `WebhookInbox.Infrastructure`. +- [x] Un test verifica que `MarkTimedOut` sobre un `Processing` vencido deja `Failed`, `LastError` `"Processing timed out"` y el mismo `AttemptCount`. +- [x] Un test verifica que `MarkTimedOut` sobre un `Processing` no vencido lanza `ProcessingNotTimedOutException`. +- [x] Un test verifica que `MarkTimedOut` con `ProcessingStartedAt` null recupera el evento. +- [x] Un test verifica que `MarkTimedOut` fuera de `Processing` lanza `InvalidEventTransitionException`. +- [x] `GlobalExceptionHandlerTests` cubre `ProcessingNotTimedOutException` → `409`. +- [x] `appsettings.json` contiene `Inbox:Recovery:ProcessingTimeout` con `"00:05:00"`. +- [x] Con `ProcessingTimeout` a `"00:00:00"` la API no arranca (falla `ValidateOnStart`). +- [x] Con Postgres levantado, `POST /inbox/events/evt-1/process` devuelve un DTO con `processingStartedAt` no nulo. +- [x] Con un evento puesto en `Processing` a mano (`UPDATE inbox_events SET status = 1, processing_started_at = now() - interval '10 minutes'`), `POST /inbox/events/{eventId}/recover` devuelve `200` con `status` `"Failed"` y `lastError` `"Processing timed out"`. +- [x] Tras eso, `POST /inbox/events/{eventId}/process` devuelve `200` con `status` `"Processed"` y `attemptCount` incrementado. +- [x] Con `processing_started_at = now()` en `Processing`, `/recover` devuelve `409` ProblemDetails. +- [x] `/recover` sobre un evento `Processed` devuelve `409`. +- [x] `POST /inbox/events/no-existe/recover` devuelve `404`. +- [x] Los endpoints existentes devuelven los mismos códigos que en SPEC 05. +- [x] `WebhookInbox.http` contiene ejemplos de `/recover`. +- [x] `CLAUDE.md` documenta `/recover`, `ProcessingStartedAt`, `ProcessingRecoveryOptions` y la fila nueva del handler. ## Decisiones