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,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.
|
||||
Reference in new issue
Block a user