Implement US-10 on-demand health insights
This commit is contained in:
1 parent
4cb6798ec9
commit
a5b269cfc3
25 files changed
+482
-4
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# US-10 Insights architecture correction
|
||||
|
||||
The decision in `Docs/Requirements/US_10_Correction` governs US-10.
|
||||
|
||||
The Insights Service is an independent process and calculates summaries on demand. Its HTTP observation client retrieves observations through the API Gateway. `InsightsController`, `InsightsApplicationService`, `InsightCalculator`, and the observation client follow `05_class_insights_service.jpg`.
|
||||
|
||||
The service has no database, repository, stored summary identifier, or generated-summary persistence. `HealthInsight` is a calculated response object. The `HealthSummary` table shown in `09_er_insights_service.jpg` is an architectural inconsistency and does not apply; this correction supersedes that table. The absence of an Insights database in `02_microservice_architecture.jpg` is intentional.
|
||||
|
||||
Each summary request uses current observations, including corrections and deletions. Trend calculation remains under US-11.
|
||||
@@ -0,0 +1,3 @@
|
||||
For US-10, the Insights Service calculates summaries on demand from observations retrieved over HTTP through the API Gateway. It does not persist generated summaries and has no database or repository.
|
||||
The HealthSummary table in Docs/Architecture/09_er_insights_service.jpg is an architectural inconsistency to be corrected, not a deferred implementation requirement. A health summary may exist as a calculated response object, without a persistence identity.
|
||||
Record this decision and reconcile the affected architecture documentation. Keep trend calculation under US-11.
|
||||
@@ -1,5 +1,6 @@
|
||||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/InsightsService/InsightsService.csproj" />
|
||||
<Project Path="src/ApiGateway/ApiGateway.csproj" />
|
||||
<Project Path="src/PatientProfileService/PatientProfileService.csproj" />
|
||||
<Project Path="src/ObservationService/ObservationService.csproj" />
|
||||
|
||||
@@ -4,3 +4,5 @@ ASPNETCORE_URLS=https://0.0.0.0:5443
|
||||
Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx
|
||||
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||
Services__Observation__BaseUrl=http://observation.example.test:5082/
|
||||
|
||||
Services__Insights__BaseUrl=http://insights.example.test:5083/
|
||||
@@ -0,0 +1,3 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_URLS=http://0.0.0.0:5083
|
||||
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=HealthApp Insights service
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=healthapp
|
||||
Group=healthapp
|
||||
WorkingDirectory=/opt/healthapp/insights
|
||||
ExecStart=/usr/bin/dotnet /opt/healthapp/insights/InsightsService.dll
|
||||
EnvironmentFile=/etc/healthapp/insights.env
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=30
|
||||
SyslogIdentifier=healthapp-insights
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,48 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ApiGateway.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class InsightsController(IHttpClientFactory clients) : ControllerBase
|
||||
{
|
||||
[HttpGet("patients/{patientId:guid}/insights")]
|
||||
public Task GetSummary(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/insights{Request.QueryString}", cancellationToken);
|
||||
|
||||
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
|
||||
try
|
||||
{
|
||||
using var upstream = await clients.CreateClient("Insights")
|
||||
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
Response.StatusCode = (int)upstream.StatusCode;
|
||||
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
|
||||
if (upstream.Headers.Location is { } location)
|
||||
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
|
||||
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
await WriteFailureAsync(StatusCodes.Status502BadGateway);
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
private Task WriteFailureAsync(int status)
|
||||
{
|
||||
if (Response.HasStarted)
|
||||
{
|
||||
HttpContext.Abort();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
Response.Clear();
|
||||
return Results.Problem(statusCode: status, title: "Insights service is unavailable.")
|
||||
.ExecuteAsync(HttpContext);
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,14 @@ public class Program
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "Observation"))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
builder.Services.AddHttpClient("Insights", (services, client) =>
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "Insights"))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
var app = builder.Build();
|
||||
_ = GetBaseUri(app.Configuration, "PatientProfile");
|
||||
_ = GetBaseUri(app.Configuration, "Observation");
|
||||
_ = GetBaseUri(app.Configuration, "Insights");
|
||||
app.UseExceptionHandler();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using InsightsService.Clients;
|
||||
using InsightsService.Domain;
|
||||
|
||||
namespace InsightsService.Application;
|
||||
|
||||
public sealed class InsightsApplicationService(ObservationServiceClient observations, InsightCalculator calculator)
|
||||
{
|
||||
public async Task<HealthInsight?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
from = NormalizeTimestamp(from);
|
||||
to = NormalizeTimestamp(to);
|
||||
if (to < from)
|
||||
throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to));
|
||||
var history = await observations.GetByPeriodAsync(patientId, from, to, cancellationToken);
|
||||
return calculator.CalculateSummary(patientId, from, to, history);
|
||||
}
|
||||
|
||||
private static DateTime NormalizeTimestamp(DateTime value) =>
|
||||
DateTime.SpecifyKind(value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(),
|
||||
DateTimeKind.Unspecified);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Globalization;
|
||||
using InsightsService.Contracts;
|
||||
|
||||
namespace InsightsService.Clients;
|
||||
|
||||
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
|
||||
{
|
||||
public async Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var start = Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture));
|
||||
var end = Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture));
|
||||
using var response = await client.GetAsync($"api/patients/{patientId}/observations?from={start}&to={end}",
|
||||
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
|
||||
?? throw new HttpRequestException("Observation history response was empty.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using InsightsService.Contracts;
|
||||
|
||||
namespace InsightsService.Clients;
|
||||
|
||||
public interface ObservationServiceClient
|
||||
{
|
||||
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace InsightsService.Contracts;
|
||||
|
||||
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace InsightsService.Contracts;
|
||||
|
||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse);
|
||||
@@ -0,0 +1,44 @@
|
||||
using InsightsService.Application;
|
||||
using InsightsService.Contracts;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
||||
namespace InsightsService.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/patients/{patientId:guid}/insights")]
|
||||
public sealed class InsightsController(InsightsApplicationService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<HealthInsightDto>> GetSummary(Guid patientId,
|
||||
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var insight = await service.GetSummaryAsync(patientId, from, to, cancellationToken);
|
||||
return insight is null
|
||||
? Problem(statusCode: StatusCodes.Status404NotFound, title: "Insufficient observation data for calculation.")
|
||||
: Ok(new HealthInsightDto(insight.PatientId, insight.PeriodStart, insight.PeriodEnd,
|
||||
insight.AverageSystolic, insight.AverageDiastolic, insight.AveragePulse,
|
||||
insight.MinSystolic, insight.MaxSystolic, insight.MinDiastolic, insight.MaxDiastolic));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
|
||||
return ValidationProblem(ModelState);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history is unavailable.");
|
||||
}
|
||||
catch (System.Text.Json.JsonException)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Observation history response is invalid.");
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Observation history timed out.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace InsightsService.Domain;
|
||||
|
||||
public sealed record HealthInsight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
||||
@@ -0,0 +1,17 @@
|
||||
using InsightsService.Contracts;
|
||||
|
||||
namespace InsightsService.Domain;
|
||||
|
||||
public sealed class InsightCalculator
|
||||
{
|
||||
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
|
||||
IReadOnlyList<ObservationDto> observations)
|
||||
{
|
||||
if (observations.Count == 0)
|
||||
return null;
|
||||
return new HealthInsight(patientId, from, to,
|
||||
observations.Average(o => (decimal)o.Systolic), observations.Average(o => (decimal)o.Diastolic),
|
||||
observations.Average(o => (decimal)o.Pulse), observations.Min(o => o.Systolic),
|
||||
observations.Max(o => o.Systolic), observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,35 @@
|
||||
using InsightsService.Application;
|
||||
using InsightsService.Clients;
|
||||
using InsightsService.Domain;
|
||||
|
||||
namespace InsightsService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddScoped<InsightsApplicationService>();
|
||||
builder.Services.AddSingleton<InsightCalculator>();
|
||||
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
|
||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
var app = builder.Build();
|
||||
_ = GetGatewayUri(app.Configuration);
|
||||
app.UseExceptionHandler();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
}
|
||||
|
||||
private static Uri GetGatewayUri(IConfiguration configuration)
|
||||
{
|
||||
var endpoint = configuration["Services:ApiGateway:BaseUrl"];
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
|
||||
(uri.Scheme != "http" && uri.Scheme != "https") || uri.AbsolutePath != "/" ||
|
||||
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) || !string.IsNullOrEmpty(uri.UserInfo))
|
||||
throw new InvalidOperationException("Services:ApiGateway:BaseUrl must be an HTTP(S) origin URL.");
|
||||
return uri;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-3
@@ -1,6 +1,6 @@
|
||||
# US-01–US-09: Patient profiles and blood-pressure observations
|
||||
# US-01–US-10: Patient profiles and blood-pressure observations
|
||||
|
||||
Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway, Patient/Profile service and Observation Service are separate executables and can run on separate machines. Each domain service owns its database.
|
||||
Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway, Patient/Profile service, Observation Service, and Insights Service are separate executables and can run on separate machines. Patient/Profile and Observation each own a database. Insights calculates on demand without persistence, following `Docs/Requirements/US_10_Correction` and `Docs/Architecture/us10-insights-correction.md`.
|
||||
|
||||
The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns.
|
||||
|
||||
@@ -18,12 +18,15 @@ dotnet run --project src/PatientProfileService -c Release --no-build -- --migrat
|
||||
ASPNETCORE_URLS=http://127.0.0.1:5081 dotnet run --project src/PatientProfileService -c Release --no-build
|
||||
|
||||
# In a separate gateway terminal.
|
||||
Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ Services__Observation__BaseUrl=http://127.0.0.1:5082/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build
|
||||
Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ Services__Observation__BaseUrl=http://127.0.0.1:5082/ Services__Insights__BaseUrl=http://127.0.0.1:5083/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build
|
||||
|
||||
# In a separate observation terminal, with its own provisioned database.
|
||||
export ConnectionStrings__ObservationDatabase='Host=127.0.0.1;Database=observations;Username=observations;Password=YOUR_LOCAL_PASSWORD'
|
||||
dotnet run --project src/ObservationService -c Release --no-build -- --migrate
|
||||
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5082 dotnet run --project src/ObservationService -c Release --no-build
|
||||
|
||||
# In a separate insights terminal; no database or migration is required.
|
||||
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5083 dotnet run --project src/InsightsService -c Release --no-build
|
||||
```
|
||||
|
||||
`--migrate` applies committed EF Core migrations and exits. Apply migrations as a deployment step before starting the service; normal startup does not modify the schema. Both services fail startup with a clear message if required configuration is absent. Configuration uses standard .NET JSON files, environment variables, and command-line arguments. Service endpoints and database hosts may be remote.
|
||||
@@ -64,6 +67,12 @@ US-08 tests cover the documented correction and rejection scenarios, correction
|
||||
|
||||
US-09 tests cover both acceptance scenarios, persistence of deletion after restart, remaining/latest observations, deletion of the only observation, repeated deletion, and preservation of other patients' observations. No new dependencies or schema changes are required.
|
||||
|
||||
`GET /api/patients/{patientId}/insights?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with `patientId`, `periodStart`, `periodEnd`, decimal `averageSystolic`, `averageDiastolic`, `averagePulse`, and integer `minSystolic`, `maxSystolic`, `minDiastolic`, `maxDiastolic`. Period validation, inclusive bounds, and timestamp normalization follow observation history. A single observation is sufficient; averages retain fractional values without deliberate rounding. An empty period returns `404` problem details with title `Insufficient observation data for calculation.` Missing/malformed/reversed bounds return `400`.
|
||||
|
||||
The independent Insights Service follows the documented controller/application-service/calculator/client design. Its HTTP observation client retrieves history through the configured gateway; there are no production project references between services. Each request recalculates from current observations, so corrections/deletions are reflected immediately. Failed observation retrieval returns `502`, and timeouts return `504`, instead of indicating insufficient data. Gateway requests to an unavailable Insights Service likewise return `502`/`504`.
|
||||
|
||||
US-10 tests use all four HTTP hosts and the existing separate patient/observation test databases. They cover all five acceptance scenarios, fractional averages, patient and inclusive-period filtering, equal/offset bounds, corrections/deletions, restart, malformed/missing periods, and unavailable observation retrieval. Insights introduces no external dependencies. Trend calculation remains outside this story.
|
||||
|
||||
Authentication and access control are defined in US-13, US-14 and `Docs/Design/authentication-and-access-control-design.md`, and remain to be implemented as separate stories, as explicitly instructed. These endpoints currently have no access restrictions.
|
||||
|
||||
## Automated acceptance tests
|
||||
@@ -91,6 +100,7 @@ Publish each service separately:
|
||||
dotnet publish src/PatientProfileService -c Release -o /tmp/healthapp-publish/patient-profile
|
||||
dotnet publish src/ApiGateway -c Release -o /tmp/healthapp-publish/api-gateway
|
||||
dotnet publish src/ObservationService -c Release -o /tmp/healthapp-publish/observation
|
||||
dotnet publish src/InsightsService -c Release -o /tmp/healthapp-publish/insights
|
||||
```
|
||||
|
||||
Copy each output to its corresponding `/opt/healthapp/` directory on the intended host, install the ASP.NET Core 10 runtime, and create a `healthapp` service user/group. Adjust the paths/user in `deploy/systemd/*.service` for the host. Copy the environment examples to `/etc/healthapp/patient-profile.env` and `/etc/healthapp/api-gateway.env`, replace example values, and restrict their permissions to protect credentials. Configure the gateway certificate for the HTTPS client entry point. Its example uses a PFX certificate; standard Kestrel configuration also supports other certificate formats.
|
||||
@@ -105,3 +115,5 @@ dotnet /opt/healthapp/observation/ObservationService.dll --migrate
|
||||
Install the corresponding unit on each host and enable/start it with systemd. The units are independent, write logs to journald, restart after failures, and allow graceful shutdown. The gateway has no systemd dependency on a local Patient/Profile process; it uses the configured network endpoint.
|
||||
|
||||
The Observation Service has its own `healthapp-observation.service` unit and environment example. Configure its `Services__ApiGateway__BaseUrl` and the gateway's `Services__Observation__BaseUrl` for the deployed hosts. Apply its migration with its own database configuration. Services need not be started in a fixed order; requests needing an unavailable upstream fail without saving observations.
|
||||
|
||||
The Insights Service has an independent `healthapp-insights.service` systemd unit and `deploy/insights.env.example`. Install its published output under `/opt/healthapp/insights`, configure `/etc/healthapp/insights.env`, and set `Services__ApiGateway__BaseUrl` to the deployed gateway. Configure the gateway's required `Services__Insights__BaseUrl` for the deployed Insights host. URLs may refer to separate machines. Insights requires no database, migration, startup ordering, or shared process state. Standard stdout/stderr logging, graceful shutdown, and restart follow the other service units.
|
||||
@@ -0,0 +1,21 @@
|
||||
# US-10 — Clarify Insights persistence
|
||||
|
||||
Resolved by `Docs/Requirements/US_10_Correction`: summaries are calculated on demand without persistence. The ER table is an inconsistency, not a deferred requirement. See `Docs/Architecture/us10-insights-correction.md`.
|
||||
|
||||
## Documents requiring reconciliation
|
||||
|
||||
- `Docs/Architecture/05_class_insights_service.jpg` shows `InsightsController`, `InsightsApplicationService`, `InsightCalculator`, and an HTTP observation client. It shows no summary repository or persistence path.
|
||||
- `Docs/Architecture/02_microservice_architecture.jpg` assigns databases to Patient/Profile and Observation, but shows no Insights database.
|
||||
- `Docs/Architecture/09_er_insights_service.jpg` defines a `HealthSummary` table with a primary key, patient identifier, period, calculated values, and generation timestamp.
|
||||
- US-10 requires calculating averages and minimum/maximum values from observations in a selected period. It does not specify storing or retrieving generated summaries.
|
||||
|
||||
The diagrams do not establish whether the ER table must be implemented for US-10 or is intended for later work. Choosing persistence changes the service's deployment, dependencies, configuration, and component responsibilities, so this is not merely an endpoint implementation detail.
|
||||
|
||||
## Proposed options, pending user decision
|
||||
|
||||
1. Calculate summaries on demand without persistence for US-10. Implement an independent ASP.NET Core Insights Service following the class diagram, obtaining period observations over HTTP through the gateway and returning fresh calculations. The ER table is deferred. This is the smallest implementation satisfying US-10 and automatically reflects corrections/deletions.
|
||||
2. Persist generated summaries in an Insights-owned PostgreSQL database using EF Core. This requires approval of the database ownership/deployment and persistence components missing from the other diagrams. Clarify whether each request records a fresh summary or reuses a stored one and how corrections/deletions affect stored results.
|
||||
|
||||
In either option, preserve service process boundaries, calculate decimal averages and integer extrema, reject invalid periods, indicate insufficient data for an empty observation set, and defer authentication as already authorized. Trend calculation belongs to US-11 and is outside US-10.
|
||||
|
||||
No authoritative documents or implementation files have been changed. This suggestion does not authorize either option.
|
||||
@@ -0,0 +1,158 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class HealthInsightTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId);
|
||||
private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
|
||||
|
||||
private async Task<Guid> PatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{ name = "Insight Example", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Guid> RecordAsync(Guid patientId, string time, int systolic, int diastolic, int pulse)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{ measuredAt = time, systolic, diastolic, pulse });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!.ObservationId;
|
||||
}
|
||||
|
||||
private string PathFor(Guid patientId, string from = "2026-09-03T00:00:00", string to = "2026-09-08T23:59:59") =>
|
||||
$"/api/patients/{patientId}/insights?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}";
|
||||
|
||||
private async Task<Insight> SummaryAsync(Guid patientId)
|
||||
{
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Insight>())!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Averages_use_only_the_requested_patient_and_period_after_restart()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-03T00:00:00", 120, 80, 60);
|
||||
await RecordAsync(patientId, "2026-09-08T23:59:59", 130, 84, 70);
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 200, 100, 90);
|
||||
await RecordAsync(patientId, "2026-09-10T08:00:00", 210, 110, 95);
|
||||
await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 220, 120, 100);
|
||||
await fixture.RestartHostsAsync();
|
||||
var insight = await SummaryAsync(patientId);
|
||||
Assert.Equal(patientId, insight.PatientId);
|
||||
Assert.Equal(new DateTime(2026, 9, 3), insight.PeriodStart);
|
||||
Assert.Equal(new DateTime(2026, 9, 8, 23, 59, 59), insight.PeriodEnd);
|
||||
Assert.Equal(125m, insight.AverageSystolic);
|
||||
Assert.Equal(82m, insight.AverageDiastolic);
|
||||
Assert.Equal(65m, insight.AveragePulse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Minimum_and_maximum_values_are_calculated()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-04T08:00:00", 118, 76, 61);
|
||||
await RecordAsync(patientId, "2026-09-05T08:00:00", 130, 84, 70);
|
||||
await RecordAsync(patientId, "2026-09-06T08:00:00", 124, 80, 66);
|
||||
var insight = await SummaryAsync(patientId);
|
||||
Assert.Equal(118, insight.MinSystolic);
|
||||
Assert.Equal(130, insight.MaxSystolic);
|
||||
Assert.Equal(76, insight.MinDiastolic);
|
||||
Assert.Equal(84, insight.MaxDiastolic);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fractional_averages_are_preserved_and_recalculated_after_correction_and_deletion()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
var first = await RecordAsync(patientId, "2026-09-04T08:00:00", 120, 80, 60);
|
||||
var second = await RecordAsync(patientId, "2026-09-05T08:00:00", 121, 81, 61);
|
||||
var initial = await SummaryAsync(patientId);
|
||||
Assert.Equal(120.5m, initial.AverageSystolic);
|
||||
Assert.Equal(80.5m, initial.AverageDiastolic);
|
||||
Assert.Equal(60.5m, initial.AveragePulse);
|
||||
using var updated = await fixture.Client.PutAsJsonAsync($"/api/observations/{second}",
|
||||
new { systolic = 130, diastolic = 84, pulse = 70 });
|
||||
Assert.Equal(HttpStatusCode.OK, updated.StatusCode);
|
||||
Assert.Equal(125m, (await SummaryAsync(patientId)).AverageSystolic);
|
||||
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
|
||||
var single = await SummaryAsync(patientId);
|
||||
Assert.Equal(120m, single.AverageSystolic);
|
||||
Assert.Equal(single.MinSystolic, single.MaxSystolic);
|
||||
using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
|
||||
using var empty = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task No_matching_observations_reports_insufficient_data()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 130, 84, 70);
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("Insufficient observation data for calculation.", problem.RootElement.GetProperty("title").GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("from=2026-09-08T00:00:00&to=2026-09-03T00:00:00")]
|
||||
[InlineData("from=invalid&to=2026-09-08T00:00:00")]
|
||||
[InlineData("from=2026-09-03T00:00:00&to=invalid")]
|
||||
[InlineData("from=2026-09-03T00:00:00")]
|
||||
[InlineData("to=2026-09-08T00:00:00")]
|
||||
[InlineData("")]
|
||||
public async Task Invalid_or_missing_period_is_rejected(string query)
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/insights?{query}");
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Equal_bounds_and_offsets_match_recording_timestamp_semantics()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 120, 80, 60);
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId,
|
||||
"2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var insight = (await response.Content.ReadFromJsonAsync<Insight>())!;
|
||||
Assert.Equal(120m, insight.AverageSystolic);
|
||||
Assert.Equal(insight.PeriodStart, insight.PeriodEnd);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unavailable_observations_report_failure_instead_of_insufficient_data()
|
||||
{
|
||||
var patientId = await PatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-05T08:00:00", 120, 80, 60);
|
||||
await fixture.StopObservationServiceAsync();
|
||||
try
|
||||
{
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patientId));
|
||||
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.RestartHostsAsync();
|
||||
}
|
||||
Assert.Equal(120m, (await SummaryAsync(patientId)).AverageSystolic);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
|
||||
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
||||
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
||||
<ProjectReference Include="../../src/InsightsService/InsightsService.csproj" />
|
||||
<ProjectReference Include="../../src/ObservationService/ObservationService.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -15,6 +15,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
private readonly string databaseName = "us04_patient_" + Guid.NewGuid().ToString("N");
|
||||
private readonly string observationDatabaseName = "us04_observation_" + Guid.NewGuid().ToString("N");
|
||||
private WebApplicationFactory<ObservationService.Program>? observation;
|
||||
private WebApplicationFactory<InsightsService.Program>? insights;
|
||||
public string ObservationConnectionString { get; private set; } = "";
|
||||
private string adminConnectionString = "";
|
||||
private WebApplicationFactory<PatientProfileService.Program>? service;
|
||||
@@ -68,6 +69,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" }));
|
||||
});
|
||||
gateway.UseKestrel(0);
|
||||
@@ -85,17 +87,33 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
observation.UseKestrel(0);
|
||||
using var observationClient = observation.CreateClient();
|
||||
gateway.Services.GetRequiredService<IConfiguration>()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString();
|
||||
insights = new WebApplicationFactory<InsightsService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString() }));
|
||||
});
|
||||
insights.UseKestrel(0);
|
||||
using var insightsClient = insights.CreateClient();
|
||||
gateway.Services.GetRequiredService<IConfiguration>()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString();
|
||||
}
|
||||
|
||||
public async Task RestartHostsAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
await observation!.DisposeAsync();
|
||||
await insights!.DisposeAsync();
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
await gateway!.DisposeAsync();
|
||||
if (service is not null) await service.DisposeAsync();
|
||||
StartHosts();
|
||||
}
|
||||
|
||||
public async Task StopObservationServiceAsync()
|
||||
{
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
observation = null;
|
||||
}
|
||||
|
||||
public async Task StopPatientServiceAsync()
|
||||
{
|
||||
await service!.DisposeAsync();
|
||||
@@ -105,6 +123,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
Client?.Dispose();
|
||||
if (insights is not null) await insights.DisposeAsync();
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
if (gateway is not null) await gateway.DisposeAsync();
|
||||
if (service is not null) await service.DisposeAsync();
|
||||
|
||||
@@ -52,6 +52,7 @@ public sealed class PatientApiFixture : IAsyncLifetime
|
||||
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" })));
|
||||
Client = gateway.CreateClient();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user