feat(workflow): document-wait task + 30-day timeout cancellation (S-10a, closes #102) (#105)
CI / build (push) Successful in 1m1s
CI / unit (push) Successful in 1m11s
CI / frontend (push) Successful in 2m33s
CI / mutation (push) Successful in 5m14s
CI / verify-stack (push) Successful in 7m37s
CI / lint (push) Successful in 1m17s

## What & why

S-10a, the **workflow/timeout spine** of the (split) document-upload slice: the registratie process
now parks at a **`WachtOpDocumenten`** user task with an **interrupting `P30D` boundary timer**. When
the documents arrive the task completes and the process continues into the diploma routing (S-13) →
Beoordelen; if the 30 days lapse, the timer cancels the wait, runs a `RegistratieVerlopen`
external-worker task, and the domain expires the aggregate to a new terminal status **`Verlopen`**.
Backend only — the real upload trigger (portal → BFF → ACL → Documenten API) is S-10b (#103).

Closes #102

Mechanism recorded in **ADR-0017**; opened as proposal #104. Mirrors the S-14 escalation
(boundary-timer + external-worker) and S-11 withdrawal (interrupting cancel) patterns.

## Definition of Done

- [x] Linked Gitea issue (above).
- [x] Failing test committed before the implementation (red→green pairs per layer).
- [x] Implementation makes the test pass.
- [x] Conventional Commits referencing the issue (`refs #102`).
- [ ] CI green — all Gitea Actions jobs (pending on this PR).
- [x] `docker compose up` health unaffected (no new services; deploy path unchanged).
- [x] Docs updated (ADR-0017, demo-script, BACKLOG split).
- [x] ADR added (`docs/architecture/adr-0017-document-wait-timeout-cancellation.md`).
- [x] Demo note in `docs/demo-script.md`.

## Notes for reviewers

- **Domain** (`Registration.Expire()` + `Verlopen`), **application** (`ExpireRegistrationWorker`),
  **infra** (`RegistratieVerlopenProcessor`/`Pump`, `IRegistratieVerlopenClient`, Flowable
  acquire/complete + `CompleteDocumentWaitAsync`) — the timeout counterpart to the OpenZaak/escalation
  worker trios; idempotent per §8.6.
- **BPMN** verified live against a `flowable-rest` probe: complete `WachtOpDocumenten` → routes to
  Beoordelen; fire the P30D timer → `RegistratieVerlopen` job (carrying `registrationId`) + the wait
  task cancelled. `verify-domain` exercises both branches in-stack (completes the wait in every existing
  block; fires the timer and asserts `Verlopen` in a new block).
- **Scope boundary:** on expiry the aggregate goes `Verlopen` and the process ends, but the ZGW *zaak*
  is not yet set to a cancellation status — that needs a new ACL method + statustype seeding and is
  folded into S-10b (noted in ADR-0017).
- `CompleteDocumentWaitAsync` is built and HTTP-tested here but not yet called from a domain endpoint;
  S-10b wires the upload trigger to it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #105
This commit was merged in pull request #105.
This commit is contained in:
not
2026-07-20 09:42:02 +00:00
parent ccae27b3da
commit 4777ff2b1d
36 changed files with 1434 additions and 69 deletions
+16
View File
@@ -27,6 +27,11 @@ public interface IDomainClient
/// unknown or not the caller's (404), so the BFF can relay a 404 rather than a 500.</summary>
Task<bool> WithdrawRegistrationAsync(string registrationId, string bsn, CancellationToken ct = default);
/// <summary>Provide the documents the caller's own registration is waiting for ("documenten
/// aanleveren"). Owner-scoped by <paramref name="bsn"/>. Returns <c>false</c> when the domain
/// reports the registration is unknown or not the caller's (404), so the BFF can relay a 404.</summary>
Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default);
/// <summary>The behandelaar's werkbak — registrations awaiting beoordeling.</summary>
Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default);
@@ -63,6 +68,17 @@ public sealed class DomainClient(HttpClient http) : IDomainClient
return true;
}
public async Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default)
{
using var response = await http.PostAsJsonAsync(
$"registrations/{registrationId}/documents", new { bsn }, ct);
// The domain 404s an unknown or not-owned registration; relay that rather than fail hard.
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
return false;
response.EnsureSuccessStatusCode();
return true;
}
public async Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default)
=> await http.GetFromJsonAsync<List<WerkbakItem>>("behandel/werkbak", ct) ?? [];
+20
View File
@@ -104,6 +104,26 @@ app.MapPost("/self-service/registrations/{id}/withdraw", async (string id, Claim
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status404NotFound);
// Self-service provide-documents (S-10a): the signed-in zorgprofessional supplies the documents their
// registration is waiting for ("documenten aanleveren"). The bsn comes from the DigiD token and is
// forwarded to the domain, which owner-scopes the action and completes the WachtOpDocumenten task; a
// registration that is unknown or not the caller's comes back 404. The real file upload + ZGW storage
// is S-10b — this is the trigger that unblocks the process.
app.MapPost("/self-service/registrations/{id}/documents", async (string id, ClaimsPrincipal user, IDomainClient domain, CancellationToken ct) =>
{
var bsn = user.FindFirstValue("bsn");
if (string.IsNullOrWhiteSpace(bsn))
return Results.BadRequest("The token carries no bsn claim.");
var provided = await domain.ProvideDocumentsAsync(id, bsn, ct);
return provided ? Results.NoContent() : Results.NotFound();
})
.RequireAuthorization()
.Produces(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status400BadRequest)
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status404NotFound);
// Openbaar register: an anonymous public lookup that exposes only public-safe fields (S-09).
app.MapGet("/openbaar/register", async (string? q, IProjectionClient projection, CancellationToken ct) =>
{
+12
View File
@@ -94,6 +94,18 @@ internal sealed class FakeDomainClient : IDomainClient
return Task.FromResult(WithdrawSucceeds);
}
public (string RegistrationId, string Bsn)? DocumentsProvidedFor { get; private set; }
/// <summary>Whether the fake domain reports the provide-documents as done (true → 204) or
/// not-found/not-owned (false → 404). Tests set this to exercise the relay.</summary>
public bool ProvideDocumentsSucceeds { get; set; } = true;
public Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default)
{
DocumentsProvidedFor = (registrationId, bsn);
return Task.FromResult(ProvideDocumentsSucceeds);
}
public (string RegistrationId, string Besluit)? Decided { get; private set; }
public Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default)
@@ -112,5 +112,46 @@ public class SelfServiceEndpointTests
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
private static HttpRequestMessage ProvideDocuments(string? bearer, string id = "reg-123")
{
var request = new HttpRequestMessage(HttpMethod.Post, $"/self-service/registrations/{id}/documents");
if (bearer is not null)
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
return request;
}
[Fact]
public async Task Rejects_providing_documents_without_a_token()
{
using var factory = new BffFactory();
var response = await factory.CreateClient().SendAsync(ProvideDocuments(bearer: null));
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Null(factory.Domain.DocumentsProvidedFor);
}
[Fact]
public async Task Provides_documents_for_the_callers_registration_forwarding_the_id_and_bsn()
{
using var factory = new BffFactory();
var response = await factory.CreateClient().SendAsync(ProvideDocuments(TestTokens.Valid("123456782"), "reg-9"));
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Equal(("reg-9", "123456782"), factory.Domain.DocumentsProvidedFor);
}
[Fact]
public async Task Relays_not_found_providing_documents_for_an_unknown_or_not_owned_registration()
{
using var factory = new BffFactory();
factory.Domain.ProvideDocumentsSucceeds = false;
var response = await factory.CreateClient().SendAsync(ProvideDocuments(TestTokens.Valid("123456782")));
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
private sealed record SubmitAcceptedDto(string RegistrationId, string Status);
}
+31
View File
@@ -61,6 +61,37 @@
}
}
},
"/self-service/registrations/{id}/documents": {
"post": {
"tags": [
"Bff.Api"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"description": "No Content"
},
"400": {
"description": "Bad Request"
},
"401": {
"description": "Unauthorized"
},
"404": {
"description": "Not Found"
}
}
}
},
"/openbaar/register": {
"get": {
"tags": [
+26
View File
@@ -22,22 +22,29 @@ builder.Services.AddTransient<IWorkflowClient>(sp => sp.GetRequiredService<Flowa
builder.Services.AddTransient<IExternalWorkerClient>(sp => sp.GetRequiredService<FlowableWorkflowClient>());
builder.Services.AddTransient<IUserTaskClient>(sp => sp.GetRequiredService<FlowableWorkflowClient>());
builder.Services.AddTransient<IBeoordelingEscalatieClient>(sp => sp.GetRequiredService<FlowableWorkflowClient>());
builder.Services.AddTransient<IRegistratieVerlopenClient>(sp => sp.GetRequiredService<FlowableWorkflowClient>());
builder.Services.AddHttpClient<IAclClient, AclHttpClient>();
builder.Services.AddScoped<SubmitRegistration>();
builder.Services.AddScoped<ApproveRegistration>();
builder.Services.AddScoped<BeoordeelRegistratie>();
builder.Services.AddScoped<WithdrawRegistration>();
builder.Services.AddScoped<ProvideDocuments>();
builder.Services.AddScoped<Werkbak>();
builder.Services.AddScoped<OpenZaakWorker>();
builder.Services.AddScoped<OpenZaakJobProcessor>();
builder.Services.AddScoped<BeoordelingEscalatieProcessor>();
builder.Services.AddScoped<ExpireRegistrationWorker>();
builder.Services.AddScoped<RegistratieVerlopenProcessor>();
// The hosted external-task job worker polls Flowable and drives OpenZaakAanmaken to completion.
builder.Services.AddHostedService<OpenZaakJobPump>();
// The escalation worker polls the BeoordelingEscaleren jobs the 14-day timer parks and reassigns
// each overdue beoordeling to the teamlead (S-14).
builder.Services.AddHostedService<BeoordelingEscalatiePump>();
// The document-timeout worker polls the RegistratieVerlopen jobs the 30-day timer on WachtOpDocumenten
// parks and expires each lapsed registration to VERLOPEN (S-10a, ADR-0017).
builder.Services.AddHostedService<RegistratieVerlopenPump>();
var app = builder.Build();
@@ -101,6 +108,23 @@ app.MapPost("/registrations/{id}/withdraw", async (string id, WithdrawRequest bo
return outcome == WithdrawOutcome.Withdrawn ? Results.NoContent() : Results.NotFound();
});
// Provide documents (S-10a): the zorgprofessional supplies the documents their registration is parked
// waiting for, completing the WachtOpDocumenten task so the process advances to beoordeling (ADR-0017).
// Owner-scoped by the caller's bsn (the BFF forwards it from the DigiD token); unknown or not-the-
// caller's is 404 (indistinguishable). Idempotent — completing an already-left wait is a no-op. The
// real file upload + ZGW storage is S-10b; this endpoint is the trigger that unblocks the process.
app.MapPost("/registrations/{id}/documents", async (string id, ProvideDocumentsRequest body, ProvideDocuments provide, CancellationToken ct) =>
{
if (!Guid.TryParse(id, out var guid))
return Results.NotFound();
if (string.IsNullOrWhiteSpace(body?.Bsn))
return Results.BadRequest(new { error = "A bsn is required to provide documents." });
var outcome = await provide.HandleAsync(new ProvideDocumentsCommand(new RegistrationId(guid), body.Bsn), ct);
return outcome == ProvideDocumentsOutcome.Accepted ? Results.NoContent() : Results.NotFound();
});
// The behandelaar's werkbak (S-12): the registrations awaiting beoordeling, read from the open
// Beoordelen user tasks (§8.2) and enriched with bsn + status. The BFF proxies this behind
// medewerker-realm + behandelaar-role authorization; the domain trusts its callers (§8.3).
@@ -128,6 +152,8 @@ public sealed record DecideRequest(string Besluit);
public sealed record WithdrawRequest(string Bsn);
public sealed record ProvideDocumentsRequest(string Bsn);
public sealed record RegistrationResponse(string RegistrationId, string Status, string? ZaakUrl);
public partial class Program;
@@ -0,0 +1,37 @@
using Big.Domain;
namespace Big.Application;
/// <summary>
/// Handles one acquired <c>RegistratieVerlopen</c> external-worker job (S-10a, ADR-0017): load the
/// registration the job correlates to and expire it to VERLOPEN — the 30-day document-wait timer fired
/// before the documents arrived, so the case is cancelled. Pure application logic over ports; it knows
/// nothing of Flowable. The polling loop that feeds it jobs lives in Infrastructure. Mirrors
/// <see cref="OpenZaakWorker"/>.
/// </summary>
public sealed class ExpireRegistrationWorker(IRegistrationStore store)
{
/// <summary>
/// Process the job. Idempotent and tolerant of races (§8.6, at-least-once delivery): a job whose
/// registration is already resolved — a redelivered expiry (VERLOPEN), or one withdrawn/decided
/// while it waited (INGETROKKEN/INGESCHREVEN/AFGEWEZEN) — is a no-op, so the job still completes
/// rather than throwing into a redelivery loop. Only a still-open registration is expired. An
/// unknown registration is an error: it throws, leaving the job un-completed for Flowable to redeliver.
/// </summary>
public async Task HandleAsync(RegistratieVerlopenJob job, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(job);
var registration = await store.GetAsync(job.RegistrationId, ct)
?? throw new InvalidOperationException(
$"No registration {job.RegistrationId} for RegistratieVerlopen job {job.JobId}.");
// Only a still-open registration lapses; an already-resolved one (expired, or withdrawn/decided
// while it waited) is left untouched so the job can complete without violating the aggregate.
if (registration.Status is not (RegistrationStatus.Ingediend or RegistrationStatus.InBehandeling))
return;
registration.Expire();
await store.SaveAsync(registration, ct);
}
}
+16
View File
@@ -25,6 +25,14 @@ public interface IWorkflowClient
/// ended, or not yet parked) it is a no-op; the aggregate is INGETROKKEN regardless.
/// </summary>
Task WithdrawProcessAsync(string processInstanceId, CancellationToken ct = default);
/// <summary>
/// Signal that the required documents have arrived (S-10a): complete the <c>WachtOpDocumenten</c>
/// user task in the instance so the process leaves the 30-day wait state and continues to
/// beoordeling (ADR-0017). Best-effort — if the instance is not parked at that task (already
/// continued, or timed out) it is a no-op. The upload trigger that calls this is wired in S-10b.
/// </summary>
Task CompleteDocumentWaitAsync(string processInstanceId, CancellationToken ct = default);
}
/// <summary>
@@ -95,3 +103,11 @@ public sealed record OpenZaakJob(string JobId, RegistrationId RegistrationId);
/// once the 14-day boundary timer fires (ADR-0015).
/// </summary>
public sealed record EscalatieJob(string JobId, string ProcessInstanceId);
/// <summary>
/// An acquired <c>RegistratieVerlopen</c> job (S-10a): the Flowable job id and the registration id it
/// carries as a process variable. The 30-day boundary timer on <c>WachtOpDocumenten</c> spawns it when
/// the required documents were not supplied in time; expiring the correlated registration to VERLOPEN
/// cancels the case (ADR-0017).
/// </summary>
public sealed record RegistratieVerlopenJob(string JobId, RegistrationId RegistrationId);
@@ -0,0 +1,47 @@
using Big.Domain;
namespace Big.Application;
/// <summary>A zorgprofessional's signal that they have supplied the documents their registration is
/// waiting for ("documenten aanleveren"). <paramref name="Bsn"/> is the authenticated caller (from the
/// DigiD token, forwarded by the BFF): only the registration's own bsn may provide its documents.</summary>
public sealed record ProvideDocumentsCommand(RegistrationId RegistrationId, string Bsn);
/// <summary>The outcome of a provide-documents request.</summary>
public enum ProvideDocumentsOutcome
{
/// <summary>The documents were accepted; the process's document wait was completed (if any).</summary>
Accepted,
/// <summary>No registration with that id belongs to the caller — unknown, or owned by someone else
/// (the two are deliberately indistinguishable, so the endpoint reveals neither).</summary>
NotFound,
}
/// <summary>
/// The provide-documents use case (S-10a): a zorgprofessional supplies the documents their registration
/// is parked waiting for, completing the WachtOpDocumenten task so the registratie process leaves the
/// 30-day wait and continues to beoordeling (ADR-0017). Owner-scoped by bsn. Completing the wait is
/// best-effort: if the registration never started a process (or already left the wait), the request
/// still stands, mirroring how <see cref="WithdrawRegistration"/> cancels best-effort. The actual file
/// upload and its ZGW storage via the ACL is S-10b; this is the trigger that unblocks the process.
/// </summary>
public sealed class ProvideDocuments(IRegistrationStore store, IWorkflowClient workflow)
{
public async Task<ProvideDocumentsOutcome> HandleAsync(ProvideDocumentsCommand command, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(command);
var registration = await store.GetAsync(command.RegistrationId, ct);
// Unknown, or not the caller's registration: report NotFound either way (don't reveal which).
if (registration is null || registration.Bsn != command.Bsn)
return ProvideDocumentsOutcome.NotFound;
// Complete the document wait (if a process is running) so beoordeling can proceed.
if (registration.ProcessInstanceId is not null)
await workflow.CompleteDocumentWaitAsync(registration.ProcessInstanceId, ct);
return ProvideDocumentsOutcome.Accepted;
}
}
+18 -2
View File
@@ -133,8 +133,24 @@ public sealed class Registration
Status = RegistrationStatus.Ingetrokken;
}
// A decision (or withdrawal) is only valid while the registration is still open (INGEDIEND or
// IN_BEHANDELING).
/// <summary>
/// Expire the registration — the 30-day document-wait timer fired before the required documents
/// were supplied, so the registratie process cancels the case (S-10a). Allowed while it is still
/// open (INGEDIEND or IN_BEHANDELING) and needs no zaak; a decided (INGESCHREVEN/AFGEWEZEN) or
/// withdrawn (INGETROKKEN) registration can no longer expire. Re-expiring one already
/// <see cref="RegistrationStatus.Verlopen"/> is a no-op — the worker job may be redelivered (§8.6).
/// </summary>
public void Expire()
{
if (Status == RegistrationStatus.Verlopen)
return;
RequireOpenForDecision(nameof(Expire));
Status = RegistrationStatus.Verlopen;
}
// A decision (or withdrawal, or expiry) is only valid while the registration is still open
// (INGEDIEND or IN_BEHANDELING).
private void RequireOpenForDecision(string decision)
{
if (Status is not (RegistrationStatus.Ingediend or RegistrationStatus.InBehandeling))
@@ -21,4 +21,8 @@ public enum RegistrationStatus
/// <summary>Withdrawn by the zorgprofessional before a decision (S-11). Terminal.</summary>
Ingetrokken,
/// <summary>Lapsed: the required documents were not supplied within the 30-day window, so the
/// registratie process cancelled the case (S-10a). Terminal.</summary>
Verlopen,
}
@@ -15,12 +15,14 @@ namespace Big.Infrastructure;
/// The REST contract here is the one verified against a live flowable-rest engine (ADR-0009).
/// </summary>
public sealed class FlowableWorkflowClient(HttpClient http, FlowableOptions options)
: IWorkflowClient, IExternalWorkerClient, IUserTaskClient, IBeoordelingEscalatieClient
: IWorkflowClient, IExternalWorkerClient, IUserTaskClient, IBeoordelingEscalatieClient, IRegistratieVerlopenClient
{
private const string Topic = "OpenZaakAanmaken";
private const string EscalatieTopic = "BeoordelingEscaleren";
private const string VerlopenTopic = "RegistratieVerlopen";
private const string ProcessDefinitionKey = "registratie";
private const string BeoordelenTaskKey = "Beoordelen";
private const string WachtOpDocumentenTaskKey = "WachtOpDocumenten";
private const string BehandelaarGroup = "behandelaar";
private const string TeamleadGroup = "teamlead";
private const string RegistrationIdVariable = "registrationId";
@@ -114,6 +116,25 @@ public sealed class FlowableWorkflowClient(HttpClient http, FlowableOptions opti
response.EnsureSuccessStatusCode();
}
public async Task CompleteDocumentWaitAsync(string processInstanceId, CancellationToken ct = default)
{
// Find the still-open WachtOpDocumenten task in this instance and complete it, so the process
// leaves the 30-day wait and continues to beoordeling (S-10a, ADR-0017). If the instance is no
// longer parked there (already continued, or the timer already cancelled it) this is a
// best-effort no-op — mirroring the withdrawal/escalation correlation (§8.6).
var query = new TaskByInstanceQueryRequest(processInstanceId, WachtOpDocumentenTaskKey);
var page = await PostAsync<TaskByInstanceQueryRequest, TaskQueryResult>(
"service/query/tasks", query, ct);
var task = page?.Data?.FirstOrDefault();
if (task is null)
return;
using var response = await SendAsync(
$"service/runtime/tasks/{task.Id}", new CompleteTaskRequest("complete", []), ct);
response.EnsureSuccessStatusCode();
}
public async Task<IReadOnlyList<EscalatieJob>> AcquireBeoordelingEscalatieJobsAsync(int maxJobs, CancellationToken ct = default)
{
var request = new AcquireJobsRequest(EscalatieTopic, options.LockDuration, maxJobs, options.WorkerId);
@@ -155,6 +176,23 @@ public sealed class FlowableWorkflowClient(HttpClient http, FlowableOptions opti
response.EnsureSuccessStatusCode();
}
public async Task<IReadOnlyList<RegistratieVerlopenJob>> AcquireRegistratieVerlopenJobsAsync(int maxJobs, CancellationToken ct = default)
{
var request = new AcquireJobsRequest(VerlopenTopic, options.LockDuration, maxJobs, options.WorkerId);
var jobs = await PostAsync<AcquireJobsRequest, List<AcquiredJob>>(
"external-job-api/acquire/jobs", request, ct) ?? [];
return [.. jobs.Select(job => new RegistratieVerlopenJob(job.Id, RegistrationId.Parse(job.RegistrationId())))];
}
public async Task CompleteRegistratieVerlopenJobAsync(string jobId, CancellationToken ct = default)
{
using var response = await SendAsync(
$"external-job-api/acquire/jobs/{jobId}/complete", new CompleteJobRequest(options.WorkerId, []), ct);
response.EnsureSuccessStatusCode();
}
private async Task<TResponse?> GetAsync<TResponse>(string path, CancellationToken ct)
{
var message = new HttpRequestMessage(HttpMethod.Get, new Uri(options.BaseUrl, path));
@@ -36,3 +36,19 @@ public interface IBeoordelingEscalatieClient
/// <summary>Complete an acquired escalation job so its token reaches the escalation end event.</summary>
Task CompleteBeoordelingEscalatieJobAsync(string jobId, CancellationToken ct = default);
}
/// <summary>
/// The document-timeout side of the Workflow Client (S-10a): the <c>RegistratieVerlopen</c>
/// external-worker jobs parked by the 30-day boundary timer on <c>WachtOpDocumenten</c>. Kept separate
/// from the other worker ports (interface segregation) so neither the OpenZaak nor escalation worker
/// sees expiry. Implemented by <see cref="FlowableWorkflowClient"/> — the only code that talks to
/// Flowable (§8.2, ADR-0017).
/// </summary>
public interface IRegistratieVerlopenClient
{
/// <summary>Acquire and lock up to <paramref name="maxJobs"/> <c>RegistratieVerlopen</c> jobs.</summary>
Task<IReadOnlyList<RegistratieVerlopenJob>> AcquireRegistratieVerlopenJobsAsync(int maxJobs, CancellationToken ct = default);
/// <summary>Complete an acquired expiry job so its token reaches the <c>endVerlopen</c> end event.</summary>
Task CompleteRegistratieVerlopenJobAsync(string jobId, CancellationToken ct = default);
}
@@ -0,0 +1,41 @@
using Big.Application;
using Microsoft.Extensions.Logging;
namespace Big.Infrastructure;
/// <summary>
/// One poll tick of the document-timeout worker (S-10a, ADR-0017): acquire the parked
/// <c>RegistratieVerlopen</c> jobs — the tokens the 30-day boundary timer on <c>WachtOpDocumenten</c>
/// spawns — expire each correlated registration via the <see cref="ExpireRegistrationWorker"/>, and
/// complete the job so its token reaches <c>endVerlopen</c>. A job that fails is logged and left
/// un-completed so Flowable redelivers it (§8.6). Split out from the hosted pump so the
/// acquire→expire→complete logic is unit-testable without a running host. Mirrors
/// <see cref="OpenZaakJobProcessor"/> and <see cref="BeoordelingEscalatieProcessor"/>.
/// </summary>
public sealed class RegistratieVerlopenProcessor(
IRegistratieVerlopenClient client,
ExpireRegistrationWorker worker,
ILogger<RegistratieVerlopenProcessor> logger)
{
/// <summary>Acquire and process up to <paramref name="maxJobs"/> jobs. Returns the number acquired.</summary>
public async Task<int> PumpOnceAsync(int maxJobs, CancellationToken ct = default)
{
var jobs = await client.AcquireRegistratieVerlopenJobsAsync(maxJobs, ct);
foreach (var job in jobs)
{
try
{
await worker.HandleAsync(job, ct);
await client.CompleteRegistratieVerlopenJobAsync(job.JobId, ct);
}
catch (Exception ex)
{
// Leave the job un-completed: its lock expires and Flowable redelivers it (§8.6).
logger.LogError(ex, "RegistratieVerlopen job {JobId} failed; leaving it for redelivery.", job.JobId);
}
}
return jobs.Count;
}
}
@@ -0,0 +1,49 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Big.Infrastructure;
/// <summary>
/// The hosted polling loop of the document-timeout worker (S-10a, ADR-0017): on an interval it
/// resolves a scoped <see cref="RegistratieVerlopenProcessor"/> and asks it to drain the parked
/// <c>RegistratieVerlopen</c> jobs. A deliberately thin shell — all acquire/expire/complete logic
/// lives in the processor, which is unit-tested; this class only owns the timer, the per-tick scope,
/// and loop resilience. Structurally identical to <see cref="BeoordelingEscalatiePump"/>.
/// </summary>
public sealed class RegistratieVerlopenPump(
IServiceScopeFactory scopeFactory,
FlowableOptions options,
ILogger<RegistratieVerlopenPump> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopeFactory.CreateScope();
var processor = scope.ServiceProvider.GetRequiredService<RegistratieVerlopenProcessor>();
await processor.PumpOnceAsync(options.MaxJobsPerPoll, stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
// A transient fault (e.g. Flowable briefly unreachable) must not kill the loop.
logger.LogError(ex, "RegistratieVerlopen job poll failed; retrying after the poll interval.");
}
try
{
await Task.Delay(options.PollInterval, stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
}
}
}
@@ -0,0 +1,84 @@
using Big.Application;
using Big.Domain;
namespace Big.Tests;
// S-10a (#102): the application handler behind the RegistratieVerlopen external-worker job. The 30-day
// document-wait timer fired, so the correlated registration is expired to VERLOPEN. Mirrors
// OpenZaakWorker — pure application logic over ports, idempotent under at-least-once delivery (§8.6).
public class ExpireRegistrationWorkerTests
{
private const string Bsn = "123456782";
private static Registration Submitted(string processInstanceId = "proc-1")
{
var registration = Registration.Submit(Bsn);
registration.RecordProcessStarted(processInstanceId);
return registration;
}
[Fact]
public async Task Expires_the_registration_the_job_correlates_to()
{
var store = new FakeRegistrationStore();
var registration = Submitted();
store.Seed(registration);
await new ExpireRegistrationWorker(store).HandleAsync(
new RegistratieVerlopenJob("job-7", registration.Id));
var saved = await store.GetAsync(registration.Id);
Assert.Equal(RegistrationStatus.Verlopen, saved!.Status);
Assert.Equal(1, store.SaveCount);
}
[Fact]
public async Task An_already_verlopen_registration_is_not_persisted_again()
{
// A redelivered job (§8.6) finds the aggregate already VERLOPEN: a no-op, not saved again.
var store = new FakeRegistrationStore();
var registration = Submitted();
registration.Expire();
store.Seed(registration);
await new ExpireRegistrationWorker(store).HandleAsync(
new RegistratieVerlopenJob("job-7", registration.Id));
Assert.Equal(0, store.SaveCount);
Assert.Equal(RegistrationStatus.Verlopen, (await store.GetAsync(registration.Id))!.Status);
}
[Fact]
public async Task An_already_resolved_registration_is_left_alone_and_the_job_completes()
{
// Race with S-11: the citizen withdrew while parked at WachtOpDocumenten, so the aggregate is
// already terminal (INGETROKKEN) when the timer's job arrives. Expiring it would violate the
// aggregate's invariant; the worker must instead no-op (and let the job complete), not throw
// into a redelivery loop.
var store = new FakeRegistrationStore();
var registration = Submitted();
registration.Withdraw();
store.Seed(registration);
await new ExpireRegistrationWorker(store).HandleAsync(
new RegistratieVerlopenJob("job-7", registration.Id));
Assert.Equal(0, store.SaveCount);
Assert.Equal(RegistrationStatus.Ingetrokken, (await store.GetAsync(registration.Id))!.Status);
}
[Fact]
public async Task An_unknown_registration_throws_so_the_job_is_redelivered()
{
var store = new FakeRegistrationStore();
await Assert.ThrowsAsync<InvalidOperationException>(() =>
new ExpireRegistrationWorker(store).HandleAsync(
new RegistratieVerlopenJob("job-7", RegistrationId.New())));
}
[Fact]
public async Task Rejects_a_null_job()
=> await Assert.ThrowsAsync<ArgumentNullException>(() =>
new ExpireRegistrationWorker(new FakeRegistrationStore()).HandleAsync(null!));
}
+7
View File
@@ -34,6 +34,7 @@ internal sealed class FakeWorkflowClient(string processInstanceId = "proc-1", Ac
public RegistrationId? StartedFor { get; private set; }
public DiplomaOrigin? StartedWithOrigin { get; private set; }
public string? WithdrawnProcessInstanceId { get; private set; }
public string? CompletedDocumentWaitFor { get; private set; }
public Task<string> StartRegistrationProcessAsync(
RegistrationId registrationId, DiplomaOrigin diplomaOrigin, CancellationToken ct = default)
@@ -49,6 +50,12 @@ internal sealed class FakeWorkflowClient(string processInstanceId = "proc-1", Ac
WithdrawnProcessInstanceId = processInstanceId;
return Task.CompletedTask;
}
public Task CompleteDocumentWaitAsync(string processInstanceId, CancellationToken ct = default)
{
CompletedDocumentWaitFor = processInstanceId;
return Task.CompletedTask;
}
}
/// <summary>A fake user-task client for the werkbak/decision use cases: returns a scripted set of
@@ -426,4 +426,106 @@ public class FlowableWorkflowClientTests
capture.Seen.RequestUri!.ToString());
Assert.Contains("\"workerId\":\"worker-x\"", capture.Body);
}
// ── S-10a (#102): document-wait timeout → RegistratieVerlopen (ADR-0017) ──────────────────────
// A 30-day interrupting boundary timer on WachtOpDocumenten spawns a RegistratieVerlopen
// external-worker job carrying the registration id; the worker expires the registration and
// completes the job. Separately, "documents received" completes the WachtOpDocumenten user task.
[Fact]
public async Task Acquire_verlopen_jobs_posts_the_topic_and_parses_jobs_with_their_registration_id()
{
var rid = RegistrationId.New();
var capture = new RequestCapture();
var client = Client(capture.Responds(HttpStatusCode.OK,
$$"""[{"id":"job-9","variables":[{"name":"registrationId","type":"string","value":"{{rid}}"}]}]"""));
var jobs = await client.AcquireRegistratieVerlopenJobsAsync(3);
var job = Assert.Single(jobs);
Assert.Equal("job-9", job.JobId);
Assert.Equal(rid, job.RegistrationId);
Assert.Equal("http://flowable/flowable-rest/external-job-api/acquire/jobs",
capture.Seen!.RequestUri!.ToString());
Assert.Contains("\"topic\":\"RegistratieVerlopen\"", capture.Body);
Assert.Contains("\"numberOfTasks\":3", capture.Body);
Assert.Contains("\"workerId\":\"worker-x\"", capture.Body);
}
[Theory]
[InlineData("[]")]
[InlineData("null")]
public async Task Acquire_verlopen_jobs_returns_empty_when_none_are_parked(string body)
{
var capture = new RequestCapture();
var client = Client(capture.Responds(HttpStatusCode.OK, body));
Assert.Empty(await client.AcquireRegistratieVerlopenJobsAsync(1));
Assert.NotNull(capture.Seen);
}
[Fact]
public async Task Complete_verlopen_job_posts_to_the_job_complete_endpoint()
{
var capture = new RequestCapture();
var client = Client(capture.Responds(HttpStatusCode.NoContent));
await client.CompleteRegistratieVerlopenJobAsync("job-9");
Assert.Equal(HttpMethod.Post, capture.Seen!.Method);
Assert.Equal("http://flowable/flowable-rest/external-job-api/acquire/jobs/job-9/complete",
capture.Seen.RequestUri!.ToString());
Assert.Contains("\"workerId\":\"worker-x\"", capture.Body);
}
[Fact]
public async Task Provide_documents_completes_the_wacht_op_documenten_task_in_the_instance()
{
var requests = new List<(HttpMethod Method, string Url, string? Body)>();
var client = Client(new StubHandler(async req =>
{
requests.Add((req.Method, req.RequestUri!.ToString(),
req.Content is null ? null : await req.Content.ReadAsStringAsync()));
return req.RequestUri!.AbsoluteUri.EndsWith("service/query/tasks")
? new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"data":[{"id":"task-3"}],"total":1}""",
Encoding.UTF8, "application/json"),
}
: new HttpResponseMessage(HttpStatusCode.OK);
}));
await client.CompleteDocumentWaitAsync("pi-1");
// 1. Find the still-open WachtOpDocumenten task in this process instance.
var query = requests.Single(r => r.Url.EndsWith("service/query/tasks"));
Assert.Equal(HttpMethod.Post, query.Method);
Assert.Contains("\"processInstanceId\":\"pi-1\"", query.Body);
Assert.Contains("\"taskDefinitionKey\":\"WachtOpDocumenten\"", query.Body);
// 2. Complete that task so the process leaves the wait state.
var complete = requests.Single(r => r.Url.EndsWith("service/runtime/tasks/task-3"));
Assert.Equal(HttpMethod.Post, complete.Method);
Assert.Contains("\"action\":\"complete\"", complete.Body);
}
[Fact]
public async Task Provide_documents_is_a_no_op_when_the_wait_task_is_no_longer_open()
{
// The process already left WachtOpDocumenten (e.g. timed out): nothing to complete, no throw.
var methods = new List<HttpMethod>();
var client = Client(new StubHandler(req =>
{
methods.Add(req.Method);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"data":[],"total":0}""", Encoding.UTF8, "application/json"),
});
}));
await client.CompleteDocumentWaitAsync("pi-1");
// Only the query ran; no task-completion POST followed.
Assert.DoesNotContain(methods, m => m == HttpMethod.Put || m == HttpMethod.Delete);
Assert.Single(methods);
}
}
@@ -0,0 +1,85 @@
using Big.Application;
using Big.Domain;
namespace Big.Tests;
// S-10a (#102): the "documents received" use case. A zorgprofessional supplies the documents their
// registration is waiting for; the handler completes the WachtOpDocumenten task via the Workflow Client
// so the process leaves the 30-day wait and continues to beoordeling. Owner-scoped by the caller's bsn,
// like WithdrawRegistration. (The real file upload + ZGW storage is S-10b; this is the trigger path.)
public class ProvideDocumentsTests
{
private const string Bsn = "123456782";
private static Registration Submitted(string processInstanceId = "proc-1")
{
var registration = Registration.Submit(Bsn);
registration.RecordProcessStarted(processInstanceId);
return registration;
}
private static ProvideDocumentsCommand Command(RegistrationId id, string bsn = Bsn) => new(id, bsn);
[Fact]
public async Task Providing_documents_completes_the_document_wait()
{
var store = new FakeRegistrationStore();
var registration = Submitted("proc-42");
store.Seed(registration);
var workflow = new FakeWorkflowClient();
var handler = new ProvideDocuments(store, workflow);
var outcome = await handler.HandleAsync(Command(registration.Id));
Assert.Equal(ProvideDocumentsOutcome.Accepted, outcome);
Assert.Equal("proc-42", workflow.CompletedDocumentWaitFor);
}
[Fact]
public async Task A_different_bsn_cannot_provide_documents()
{
// Owner-scoping: only the registration's own bsn may supply its documents. Another bsn is told
// NotFound (existence not revealed) and the wait is not completed.
var store = new FakeRegistrationStore();
var registration = Submitted();
store.Seed(registration);
var workflow = new FakeWorkflowClient();
var handler = new ProvideDocuments(store, workflow);
var outcome = await handler.HandleAsync(Command(registration.Id, bsn: "999999990"));
Assert.Equal(ProvideDocumentsOutcome.NotFound, outcome);
Assert.Null(workflow.CompletedDocumentWaitFor);
}
[Fact]
public async Task Providing_for_an_unknown_registration_is_not_found()
{
var store = new FakeRegistrationStore();
var handler = new ProvideDocuments(store, new FakeWorkflowClient());
Assert.Equal(ProvideDocumentsOutcome.NotFound, await handler.HandleAsync(Command(RegistrationId.New())));
}
[Fact]
public async Task Providing_before_a_process_started_is_accepted_without_calling_the_workflow()
{
// No process yet → no wait task to complete; the request still stands (best-effort, mirroring
// WithdrawRegistration) and the Workflow Client is not called.
var store = new FakeRegistrationStore();
var registration = Registration.Submit(Bsn); // no RecordProcessStarted
store.Seed(registration);
var workflow = new FakeWorkflowClient();
var handler = new ProvideDocuments(store, workflow);
var outcome = await handler.HandleAsync(Command(registration.Id));
Assert.Equal(ProvideDocumentsOutcome.Accepted, outcome);
Assert.Null(workflow.CompletedDocumentWaitFor);
}
[Fact]
public async Task Rejects_a_null_command()
=> await Assert.ThrowsAsync<ArgumentNullException>(() =>
new ProvideDocuments(new FakeRegistrationStore(), new FakeWorkflowClient()).HandleAsync(null!));
}
@@ -0,0 +1,79 @@
using Big.Application;
using Big.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Big.Tests;
// S-10a (#102): the document-timeout drain loop. Mirrors BeoordelingEscalatieProcessor — acquire the
// parked RegistratieVerlopen jobs (the tokens the 30-day boundary timer on WachtOpDocumenten spawns),
// expire each correlated registration via the ExpireRegistrationWorker, then complete the job. A job
// whose expiry fails is logged and left un-completed for Flowable to redeliver (§8.6).
public class RegistratieVerlopenProcessorTests
{
/// <summary>A fake client scripting the jobs to acquire and recording completions.</summary>
private sealed class FakeVerlopenClient(params RegistratieVerlopenJob[] jobs) : IRegistratieVerlopenClient
{
public int AcquireCount { get; private set; }
public List<string> Completed { get; } = [];
public Task<IReadOnlyList<RegistratieVerlopenJob>> AcquireRegistratieVerlopenJobsAsync(int maxJobs, CancellationToken ct = default)
{
AcquireCount++;
return Task.FromResult<IReadOnlyList<RegistratieVerlopenJob>>(jobs.Take(maxJobs).ToList());
}
public Task CompleteRegistratieVerlopenJobAsync(string jobId, CancellationToken ct = default)
{
Completed.Add(jobId);
return Task.CompletedTask;
}
}
private static ExpireRegistrationWorker Worker(FakeRegistrationStore store) => new(store);
[Fact]
public async Task Acquires_a_job_expires_the_registration_and_completes_the_job()
{
var store = new FakeRegistrationStore();
var registration = Domain.Registration.Submit("123456782");
store.Seed(registration);
var client = new FakeVerlopenClient(new RegistratieVerlopenJob("job-9", registration.Id));
var acquired = await new RegistratieVerlopenProcessor(
client, Worker(store), NullLogger<RegistratieVerlopenProcessor>.Instance).PumpOnceAsync(5);
Assert.Equal(1, acquired);
Assert.Equal(Domain.RegistrationStatus.Verlopen, (await store.GetAsync(registration.Id))!.Status);
Assert.Equal("job-9", Assert.Single(client.Completed));
}
[Fact]
public async Task A_failing_expiry_is_left_uncompleted_for_flowable_to_redeliver()
{
// Unknown registration → the worker throws → the job is left for redelivery, error logged.
var store = new FakeRegistrationStore();
var client = new FakeVerlopenClient(new RegistratieVerlopenJob("job-9", Domain.RegistrationId.New()));
var logger = new CapturingLogger<RegistratieVerlopenProcessor>();
var acquired = await new RegistratieVerlopenProcessor(client, Worker(store), logger).PumpOnceAsync(5);
Assert.Equal(1, acquired);
Assert.Empty(client.Completed);
var error = Assert.Single(logger.Entries, e => e.Level == LogLevel.Error);
Assert.Contains("job-9", error.Message);
}
[Fact]
public async Task Does_nothing_but_poll_when_there_are_no_jobs()
{
var client = new FakeVerlopenClient();
var acquired = await new RegistratieVerlopenProcessor(
client, Worker(new FakeRegistrationStore()), NullLogger<RegistratieVerlopenProcessor>.Instance).PumpOnceAsync(5);
Assert.Equal(0, acquired);
Assert.Equal(1, client.AcquireCount);
Assert.Empty(client.Completed);
}
}
@@ -294,4 +294,63 @@ public class RegistrationTests
Assert.Contains("only an INGEDIEND", ex.Message);
Assert.Equal(RegistrationStatus.Afgewezen, registration.Status);
}
[Fact]
public void Expiring_an_ingediend_registration_sets_it_verlopen()
{
// The 30-day document-wait timer fired before the documents arrived (S-10a): the case is
// cancelled and the aggregate becomes terminal VERLOPEN.
var registration = Registration.Submit("123456782");
registration.Expire();
Assert.Equal(RegistrationStatus.Verlopen, registration.Status);
}
[Fact]
public void Expiring_needs_no_zaak()
{
// The timer fires on a purely time-based boundary; expiry does not depend on the zaak.
var registration = Registration.Submit("123456782");
registration.Expire();
Assert.Equal(RegistrationStatus.Verlopen, registration.Status);
Assert.Null(registration.ZaakUrl);
}
[Fact]
public void Re_expiring_an_already_verlopen_registration_is_idempotent()
{
// The RegistratieVerlopen worker job may be redelivered (§8.6); re-expiring is a no-op.
var registration = Registration.Submit("123456782");
registration.Expire();
registration.Expire();
Assert.Equal(RegistrationStatus.Verlopen, registration.Status);
}
[Fact]
public void Expiring_an_approved_registration_is_rejected()
{
var registration = Registration.Submit("123456782");
registration.AttachZaak(new Uri("http://openzaak/zaken/api/v1/zaken/abc"));
registration.Approve();
var ex = Assert.Throws<InvalidOperationException>(() => registration.Expire());
Assert.Contains("only an INGEDIEND", ex.Message);
Assert.Equal(RegistrationStatus.Ingeschreven, registration.Status);
}
[Fact]
public void Expiring_a_withdrawn_registration_is_rejected()
{
var registration = Registration.Submit("123456782");
registration.Withdraw();
var ex = Assert.Throws<InvalidOperationException>(() => registration.Expire());
Assert.Contains("only an INGEDIEND", ex.Message);
Assert.Equal(RegistrationStatus.Ingetrokken, registration.Status);
}
}
+2 -1
View File
@@ -5,7 +5,8 @@
"reporters": ["progress", "html"],
"mutate": [
"!**/OpenZaakJobPump.cs",
"!**/BeoordelingEscalatiePump.cs"
"!**/BeoordelingEscalatiePump.cs",
"!**/RegistratieVerlopenPump.cs"
],
"thresholds": {
"high": 95,