Implement US-12 consolidated health overview service
This commit is contained in:
1 parent
cc76c9bde4
commit
076e675c81
26 files changed
+804
-16
No files matched your search
+17
-3
@@ -181,6 +181,20 @@ The US-14 tests exercise actual login, multiple and shared assignments, empty li
|
||||
assigned/unassigned reads, preserved context, missing resources, every existing
|
||||
write route, invalid and expired credentials, patient-role rejection, assignment
|
||||
changes across restart and unavailable ownership lookup. Trend and overview
|
||||
endpoints are still absent: their read routing and integration tests must be added
|
||||
with US-11/US-12. Structured context remains work under US-04–US-08; professional
|
||||
access already applies to whatever observation context those APIs expose.
|
||||
endpoints now have equivalent owner/assignment routing and integration tests under
|
||||
US-11/US-12. Structured observation context is included in authorized reads.
|
||||
|
||||
## US-12 Overview service access
|
||||
|
||||
The gateway requires `Services:HealthOverview:BaseUrl` and `Services:HealthOverview:Key`.
|
||||
The latter matches Overview's `InternalAccess:GatewayKey` and protects direct access.
|
||||
Overview's outgoing `Services:ApiGateway:Key` matches `InternalAccess:HealthOverview:Key`
|
||||
on the gateway. Use distinct randomly generated credentials of at least 32 characters
|
||||
for each direction and service; load them externally. Production endpoints use HTTPS.
|
||||
|
||||
The HealthOverview service identity is restricted to GET patient profiles, GET latest
|
||||
overall observations and GET numerical insights. It cannot retrieve history, trends or
|
||||
another overview, or perform writes. It establishes no client identity. The gateway
|
||||
checks client ownership/professional assignment before forwarding the outer request.
|
||||
Internal credentials are trusted service credentials and must remain inaccessible to clients.
|
||||
Overview adds no authentication framework, shared runtime library or persistence.
|
||||
@@ -0,0 +1,48 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ApiGateway.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class HealthOverviewController(IHttpClientFactory clients) : ControllerBase
|
||||
{
|
||||
[HttpGet("patients/{patientId:guid}/overview")]
|
||||
public Task GetOverview(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/overview{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("HealthOverview")
|
||||
.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: "Health overview service is unavailable.")
|
||||
.ExecuteAsync(HttpContext);
|
||||
}
|
||||
}
|
||||
@@ -62,11 +62,20 @@ public class Program
|
||||
})
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
builder.Services.AddHttpClient("HealthOverview", (services, client) =>
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
client.BaseAddress = GetBaseUri(configuration, "HealthOverview");
|
||||
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:HealthOverview:Key"]);
|
||||
})
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
var app = builder.Build();
|
||||
_ = GetBaseUri(app.Configuration, "PatientProfile");
|
||||
_ = GetBaseUri(app.Configuration, "Observation");
|
||||
_ = GetBaseUri(app.Configuration, "Insights");
|
||||
foreach (var key in new[] { "Services:PatientProfile:Key", "Services:Observation:Key", "Services:Insights:Key", "InternalAccess:Observation:Key", "InternalAccess:Insights:Key" })
|
||||
_ = GetBaseUri(app.Configuration, "HealthOverview");
|
||||
foreach (var key in new[] { "Services:PatientProfile:Key", "Services:Observation:Key", "Services:Insights:Key", "Services:HealthOverview:Key", "InternalAccess:HealthOverview:Key", "InternalAccess:Observation:Key", "InternalAccess:Insights:Key" })
|
||||
if (string.IsNullOrWhiteSpace(app.Configuration[key]) || app.Configuration[key]!.Length < 32)
|
||||
throw new InvalidOperationException($"{key} must contain at least 32 characters.");
|
||||
if (string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"]))
|
||||
@@ -74,7 +83,7 @@ public class Program
|
||||
var lifetime = app.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30);
|
||||
if (lifetime <= 0 || lifetime > 1440) throw new InvalidOperationException("Token lifetime must be between 1 and 1440 minutes.");
|
||||
if (!app.Environment.IsDevelopment())
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights" })
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
|
||||
if (GetBaseUri(app.Configuration, service).Scheme != "https")
|
||||
throw new InvalidOperationException("Production service endpoints must use HTTPS.");
|
||||
_ = app.Services.GetRequiredService<PrototypeAccounts>();
|
||||
|
||||
@@ -14,7 +14,7 @@ public sealed class InternalServiceAuthenticationHandler(IOptionsMonitor<Authent
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var supplied = Request.Headers["X-Service-Key"].ToString();
|
||||
foreach (var service in new[] { "Observation", "Insights" })
|
||||
foreach (var service in new[] { "Observation", "Insights", "HealthOverview" })
|
||||
{
|
||||
var expected = configuration[$"InternalAccess:{service}:Key"]!;
|
||||
if (CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(expected)))
|
||||
|
||||
@@ -21,9 +21,17 @@ public sealed class PatientAccessMiddleware(RequestDelegate next)
|
||||
if (context.User.IsInRole("Service"))
|
||||
{
|
||||
var service = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
var allowed = context.Request.Method == "GET" && segments.Length == (service == "Observation" ? 3 : 4)
|
||||
&& segments[0] == "api" && segments[1] == "patients" && Guid.TryParse(segments[2], out _)
|
||||
&& (service == "Observation" || segments[3] == "observations");
|
||||
var patientRoute = segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
|
||||
&& Guid.TryParse(segments[2], out _);
|
||||
var allowed = context.Request.Method == "GET" && patientRoute && (service switch
|
||||
{
|
||||
"Observation" => segments.Length == 3,
|
||||
"Insights" => segments.Length == 4 && segments[3] == "observations",
|
||||
"HealthOverview" => segments.Length == 3 ||
|
||||
(segments.Length == 4 && segments[3] == "insights") ||
|
||||
(segments.Length == 5 && segments[3] == "observations" && segments[4] == "latest"),
|
||||
_ => false
|
||||
});
|
||||
if (!allowed) { context.Response.StatusCode = 403; return; }
|
||||
await next(context);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using HealthOverviewService.Clients;
|
||||
using HealthOverviewService.Contracts;
|
||||
|
||||
namespace HealthOverviewService.Application;
|
||||
|
||||
public sealed class HealthOverviewApplicationService(PatientProfileServiceClient patients,
|
||||
ObservationServiceClient observations, InsightsServiceClient insights)
|
||||
{
|
||||
public async Task<HealthOverviewDto?> GetOverviewAsync(Guid patientId, DateTime from, DateTime to,
|
||||
ContextSelection selection, 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));
|
||||
Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true);
|
||||
var patient = await patients.GetPatientAsync(patientId, cancellationToken);
|
||||
if (patient is null) return null;
|
||||
var latest = await observations.GetLatestAsync(patientId, cancellationToken);
|
||||
var insight = await insights.GetSummaryAsync(patientId, from, to, selection, cancellationToken);
|
||||
return new(patient, latest, insight, from, to, selection, insight?.ContributingCount ?? 0,
|
||||
"Latest overall observation for the patient, independent of the insight period and context selections. " +
|
||||
"Its recorded context applies only to that observation, not to the insight's contributing observations.",
|
||||
insight is null ? "No calculated insight is available: no observations match the requested period and insight selection." :
|
||||
"The insight uses the requested period and context selection only. " + insight.ContextExplanation);
|
||||
}
|
||||
|
||||
private static DateTime NormalizeTimestamp(DateTime value) => DateTime.SpecifyKind(
|
||||
value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(), DateTimeKind.Unspecified);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using HealthOverviewService.Contracts;
|
||||
|
||||
namespace HealthOverviewService.Clients;
|
||||
|
||||
public abstract class InsightsServiceClient
|
||||
{
|
||||
public abstract Task<HealthInsightDto?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class HttpInsightsServiceClient(HttpClient client) : InsightsServiceClient
|
||||
{
|
||||
public override async Task<HealthInsightDto?> GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = $"api/patients/{patientId}/insights";
|
||||
path += $"?from={Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture))}&to={Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture))}";
|
||||
if (selection.Setting is not null) path += "&setting=" + Uri.EscapeDataString(selection.Setting);
|
||||
if (selection.ActivityCondition is not null) path += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition);
|
||||
|
||||
using var response = await client.GetAsync(path, cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound) return null;
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<HealthInsightDto>(cancellationToken)
|
||||
?? throw new JsonException("Empty upstream response.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using HealthOverviewService.Contracts;
|
||||
|
||||
namespace HealthOverviewService.Clients;
|
||||
|
||||
public abstract class ObservationServiceClient
|
||||
{
|
||||
public abstract Task<ObservationDto?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient
|
||||
{
|
||||
public override async Task<ObservationDto?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = $"api/patients/{patientId}/observations/latest";
|
||||
using var response = await client.GetAsync(path, cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound) return null;
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<ObservationDto>(cancellationToken)
|
||||
?? throw new JsonException("Empty upstream response.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using HealthOverviewService.Contracts;
|
||||
|
||||
namespace HealthOverviewService.Clients;
|
||||
|
||||
public abstract class PatientProfileServiceClient
|
||||
{
|
||||
public abstract Task<PatientDto?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class HttpPatientProfileServiceClient(HttpClient client) : PatientProfileServiceClient
|
||||
{
|
||||
public override async Task<PatientDto?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = $"api/patients/{patientId}";
|
||||
using var response = await client.GetAsync(path, cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound) return null;
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<PatientDto>(cancellationToken)
|
||||
?? throw new JsonException("Empty upstream response.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthOverviewService.Contracts;
|
||||
|
||||
public sealed record ContextSelection
|
||||
{
|
||||
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||
public string? Setting { get; init; }
|
||||
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||
public string? ActivityCondition { get; init; }
|
||||
}
|
||||
|
||||
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
|
||||
public sealed record MeasurementContextDto(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
|
||||
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
|
||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, MeasurementContextDto MeasurementContext);
|
||||
public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
|
||||
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
|
||||
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic,
|
||||
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
|
||||
public sealed record HealthOverviewDto(PatientDto Patient, ObservationDto? LatestObservation, HealthInsightDto? Insight,
|
||||
DateTime PeriodStart, DateTime PeriodEnd, ContextSelection InsightSelection, int InsightContributingCount,
|
||||
string LatestObservationBasis, string InsightExplanation);
|
||||
@@ -0,0 +1,34 @@
|
||||
using HealthOverviewService.Application;
|
||||
using HealthOverviewService.Contracts;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
||||
namespace HealthOverviewService.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/patients/{patientId:guid}/overview")]
|
||||
public sealed class HealthOverviewController(HealthOverviewApplicationService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<HealthOverviewDto>> GetOverview(Guid patientId,
|
||||
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
|
||||
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.GetOverviewAsync(patientId, from, to, selection, cancellationToken);
|
||||
return result is null ? Problem(statusCode: 404, title: "Patient does not exist.") : Ok(result);
|
||||
}
|
||||
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: 502, title: "Overview source service is unavailable."); }
|
||||
catch (System.Text.Json.JsonException)
|
||||
{ return Problem(statusCode: 502, title: "Overview source response is invalid."); }
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{ return Problem(statusCode: 504, title: "Overview source request timed out."); }
|
||||
}
|
||||
}
|
||||
@@ -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,78 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using HealthOverviewService.Application;
|
||||
using HealthOverviewService.Clients;
|
||||
|
||||
namespace HealthOverviewService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddScoped<HealthOverviewApplicationService>();
|
||||
builder.Services.AddHttpClient<PatientProfileServiceClient, HttpPatientProfileServiceClient>((services, client) =>
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
client.BaseAddress = GetGatewayUri(configuration);
|
||||
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||
})
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
client.BaseAddress = GetGatewayUri(configuration);
|
||||
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||
})
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
builder.Services.AddHttpClient<InsightsServiceClient, HttpInsightsServiceClient>((services, client) =>
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
client.BaseAddress = GetGatewayUri(configuration);
|
||||
var serviceKey = configuration["Services:ApiGateway:Key"];
|
||||
if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32)
|
||||
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||
client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey);
|
||||
})
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
var app = builder.Build();
|
||||
if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https")
|
||||
throw new InvalidOperationException("Production gateway endpoints must use HTTPS.");
|
||||
_ = GetGatewayUri(app.Configuration);
|
||||
var outgoingKey = app.Configuration["Services:ApiGateway:Key"];
|
||||
if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32)
|
||||
throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters.");
|
||||
var gatewayKey = app.Configuration["InternalAccess:GatewayKey"];
|
||||
if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32)
|
||||
throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters.");
|
||||
app.UseExceptionHandler();
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var supplied = context.Request.Headers["X-Gateway-Key"].ToString();
|
||||
if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) ||
|
||||
!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey)))
|
||||
{ context.Response.StatusCode = 401; return; }
|
||||
await next(context);
|
||||
});
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# US-12 health overview
|
||||
|
||||
`GET /api/patients/{patientId}/overview?from=...&to=...&setting=Home&activityCondition=AtRest`
|
||||
requires the patient's authenticated account or an assigned read-only professional.
|
||||
Dates use the existing inclusive measurement-instant convention. Offset-free timestamps
|
||||
mean UTC; equivalent offsets identify the same instant. From and to are required,
|
||||
equal bounds are valid, reversed/malformed/missing bounds return 400. Both selected
|
||||
context dimensions must match for insight; `Unknown` is an explicit selectable category.
|
||||
Omitted dimensions are unrestricted. Unsupported selections return 400 validation details.
|
||||
|
||||
The independent ASP.NET Core Health Overview Service loads the profile, latest overall
|
||||
observation and US-10 numerical insight through three HTTP clients routed through the
|
||||
gateway. It has no production project references to another service, database, stored
|
||||
aggregate or cache. The renamed Overview ER illustration explicitly denotes data needed
|
||||
from other services rather than overview persistence; the current class model governs.
|
||||
|
||||
## Response
|
||||
|
||||
A successful request returns 200 with:
|
||||
|
||||
- `patient`: the current profile, including ID, name, birth date and contact information.
|
||||
- `latestObservation`: latest overall reading, including original text, note and all recorded
|
||||
structured context, or null when no observations exist. Latest retains US-06 timestamp,
|
||||
original recording-time and deterministic ID ordering. The insight period and filters
|
||||
never limit latest-observation selection.
|
||||
- `insight`: the existing US-10 response or null when no observations match the insight
|
||||
period/context. Its rounded means, extrema, selection, contributing count and context
|
||||
explanation are preserved. No trend component is added.
|
||||
- `periodStart`, `periodEnd`, `insightSelection`, `insightContributingCount`: explicit insight
|
||||
basis even when insight is absent (count zero).
|
||||
- `latestObservationBasis`: explains that latest context belongs to that reading only.
|
||||
- `insightExplanation`: preserves the insight's context limitations or explains why no
|
||||
selected-period insight is available. Empty insight does not remove profile/latest.
|
||||
|
||||
An authorized missing patient returns 404 with `Patient does not exist.` Access rejection
|
||||
retains the gateway's non-disclosing empty 404 convention; unauthenticated clients get 401.
|
||||
Professional writes remain forbidden. Upstream connection/status/invalid-JSON failures
|
||||
return 502; local upstream timeouts return 504. These are not reported as absent data.
|
||||
Only upstream 404 responses on the appropriate profile/latest/insight routes represent
|
||||
missing data. Requests are cancelled on client disconnect.
|
||||
|
||||
Every overview request fetches current source data, including profile updates, corrected
|
||||
measurement/context, and deletions. Reads occur separately across services, so concurrent
|
||||
writes may occur between them; the overview does not promise a cross-service snapshot.
|
||||
There is no extra transaction, refresh mechanism, synchronisation process or persisted
|
||||
copy to invalidate.
|
||||
|
||||
## Deployment and verification
|
||||
|
||||
The service builds/publishes independently with .NET 10 and starts from external
|
||||
configuration. See `deploy/health-overview.env.example`, the independent systemd unit,
|
||||
[README.md](README.md) and [AUTHENTICATION.md](AUTHENTICATION.md). It requires only the
|
||||
gateway origin and incoming/outgoing service credentials; no database configuration or
|
||||
migration is needed. Production uses HTTPS; local HTTP is limited to Development.
|
||||
Addresses, network binding, credentials and certificates are configurable for separate
|
||||
machines. Standard stdout/stderr logging, graceful shutdown and restart follow the other
|
||||
service units. No new package dependencies are introduced.
|
||||
|
||||
US-12 acceptance tests run five actual HTTP hosts against separate patient/observation
|
||||
PostgreSQL databases. They cover all story scenarios, boundaries/offsets, patient scope,
|
||||
latest tie rules, context preservation, independent filters, unknown/mixed context,
|
||||
empty selected insight, corrections/deletions/restart, profile updates, missing patients,
|
||||
validation, owner/assignment enforcement, direct bypass rejection, restricted internal
|
||||
service reads and unavailable upstream/Overview services.
|
||||
+22
-3
@@ -1,6 +1,6 @@
|
||||
# Patient profiles, observations, insights and authentication
|
||||
# Patient profiles, observations, insights, overview and authentication
|
||||
|
||||
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/Architecture/us10-insights-correction.md`.
|
||||
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, Insights Service, and Health Overview 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/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.
|
||||
|
||||
@@ -28,7 +28,7 @@ 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/ 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
|
||||
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/ Services__HealthOverview__BaseUrl=http://127.0.0.1:5084/ 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'
|
||||
@@ -37,6 +37,9 @@ Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.
|
||||
|
||||
# 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
|
||||
|
||||
# In a separate overview terminal; no database or migration is required.
|
||||
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5084 dotnet run --project src/HealthOverviewService -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.
|
||||
@@ -233,6 +236,14 @@ reproducible mathematical methods, reference sources and interpretation limits.
|
||||
all US-11 acceptance criteria, current corrections/context/deletion, access controls and failures.
|
||||
No persistence, service boundaries, dependencies or configuration changed.
|
||||
|
||||
`GET /api/patients/{patientId}/overview?from=...&to=...` implements US-12 in the
|
||||
independently deployable Health Overview Service. It returns the current profile,
|
||||
latest overall observation with its own recorded context, and selected-period numerical
|
||||
insight. Setting/activity filters apply to insight only. Empty insight selections keep
|
||||
the profile and latest reading and explain the missing insight. Context limitations,
|
||||
applied selections and counts remain visible. See [OVERVIEW.md](OVERVIEW.md) for
|
||||
response semantics, service credentials, deployment and consistency limits.
|
||||
|
||||
US-13 authentication and patient ownership are implemented as described in
|
||||
[AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted
|
||||
in the patient service. US-14 professional reads require predefined gateway assignments; professional
|
||||
@@ -293,6 +304,7 @@ dotnet publish src/PatientProfileService -c Release -o /tmp/healthapp-publish/pa
|
||||
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
|
||||
dotnet publish src/HealthOverviewService -c Release -o /tmp/healthapp-publish/health-overview
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -309,3 +321,10 @@ Install the corresponding unit on each host and enable/start it with systemd. Th
|
||||
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.
|
||||
|
||||
The Health Overview Service has its own `healthapp-health-overview.service` unit and
|
||||
`deploy/health-overview.env.example`. Publish to `/opt/healthapp/health-overview` and
|
||||
configure `/etc/healthapp/health-overview.env`. Set its `Services__ApiGateway__BaseUrl`
|
||||
and the gateway's `Services__HealthOverview__BaseUrl` to the deployed hosts. The
|
||||
gateway now requires the Overview endpoint and both directions of service credentials.
|
||||
Overview owns no database and requires no migrations or fixed startup order.
|
||||
Reference in new issue
Block a user