Record Architecture B approval and verified pinned baseline

This commit is contained in:
Steffen committed 2026-10-14 10:58:43 +02:00
1 parent 20ab461c01
commit cee98e7035
158 files changed
+33575

No files matched your search

@@ -0,0 +1,200 @@
# US-13 prototype authentication
The API gateway authenticates pre-created externally configured accounts. Login is
`POST /api/authentication/login` with `accountId` and `password`. A successful JSON
response contains `accessToken`, `tokenType: Bearer`, `expiresIn`, `accountId` and
trusted `role`; it contains no patient data or refresh token. Send the access token
as `Authorization: Bearer <token>` on subsequent patient-data requests. Invalid
credentials return the same `401` response for unknown accounts and wrong passwords.
Login responses cannot be cached. General measurement guidance remains public.
## Mechanism and configuration
Use ASP.NET Core's built-in bearer authentication and ticket protection, with
Data Protection's application name `HealthApp.ApiGateway` and the bearer purpose.
Tokens are opaque protected authentication tickets, not JWTs. The configured key
ring and framework purpose enforce the gateway trust boundary; only account ID,
role and authentication properties are protected inside a token. Do not share the
key ring with other applications/services. No custom cryptography, identity
microservice, account database or refresh-token mechanism is introduced.
The gateway verifies passwords with ASP.NET Core `PasswordHasher` against
`Authentication:Accounts:<index>:{AccountId,Role,PasswordHash}`. Roles are `Patient`
or `HealthcareProfessional`, from trusted configuration. IDs support ASCII letters,
digits, hyphen and underscore, up to 128 characters. This keeps the internal account
lookup contract unambiguous. Provision credentials externally; no registration or
administration API is exposed. For provisioning, `tools/PasswordHash` reads a
password from standard input and emits its ASP.NET Core hash. Supply input securely
(e.g. redirect a permission-restricted temporary file), and protect the resulting
hash/configuration; neither belongs in Git. The tool needs no NuGet dependency.
`Authentication:TokenLifetimeMinutes` defaults to 30; supported range is 1–1440.
`Authentication:KeyDirectory` is required. Keep its contents persistent through
restart/deployment and readable only by the gateway service account. The systemd
unit provides a mode-0700 state directory; example configuration points into it.
Keys are protected by filesystem permissions in this Linux prototype. Removing
keys invalidates tokens; preserve them for restart continuity. Accounts and
configuration are loaded at startup; after disabling accounts or changing roles,
old tokens can remain valid until their expiry. Immediate revocation is outside
this story. Missing/invalid/expired tokens return `401`; authenticate again after
expiry. Credential validation is not repeated for each operation.
Before thesis measurement, record the lifetime, account/role mix, key persistence,
login frequency and expiry handling. Normally obtain tokens during workload setup
and reuse them; state explicitly whether login is measured. If tokens expire,
re-authentication is required. Keep these choices identical across variants. The
automated test helper logs in using real password verification and caches tokens;
its account-per-resource setup is not a prescribed measurement workload.
## Ownership and profile creation
The patient service owns the account association as `patient.account_id` with a
unique index. It remains application access data, outside tokens. The gateway
queries its protected `GET /api/patients/by-account/{accountId}` service API on each
request; that API is not forwarded as a public account-lookup route. An account
without a profile may log in and create one; its other own-data requests return
`404`. Patient operations are subject to the standard Patient authorization policy.
`GET /api/patients/me` retrieves the caller’s own associated profile without needing
to know its generated identifier, including after a creation response was lost.
It returns `404` before profile creation.
Profile creation derives `X-Account-Id` from the authenticated principal. The
gateway overwrites client input; the service accepts it only behind its gateway
credential. The profile and association are inserted in one atomic database save,
so failure rolls both back. The unique index arbitrates concurrent creation. A
completed creation, a retry after a lost response and a competing request cannot
create another profile; later attempts receive `409`. A retry after a failed
transaction may create the first profile. Profile identity remains persistent
through restarts. US-01's authenticated creation is included because US-13 depends
on a persistent, recoverable association.
Apply the new patient migration before startup. Existing profiles retain a null
account association rather than being assigned to an arbitrary account. They are
not accessible to patient accounts until a trusted deployment operator explicitly
associates them with pre-created accounts. For synthetic experiments, provision a
fresh database via the authenticated creation flow. Do not infer ownership from
caller-supplied IDs or automatically assign historical profiles.
For observation-ID requests, the gateway reads the observation through its service
API to obtain the actual patient, then compares that owner with the account's
profile. Requests for another patient's information receive an empty `404`, the
same as missing data, without forwarding writes or revealing existence. Failed
ownership lookups fail closed with `502`/`504`. Tokens do not cache ownership.
Healthcare-professional logins establish a trusted role. US-14 now permits reads
of assigned patients and the caller’s own assignment list; all professional writes
are rejected before forwarding. Trend/overview endpoints remain unimplemented; the
gateway's default authentication policy also protects future patient endpoints,
which must retain ownership checks when added.
## Service and transport protection
Use HTTPS for client and service traffic. Outside Development, gateway and service
requests over HTTP are rejected and outgoing service endpoints must be HTTPS.
Certificates use ordinary Kestrel configuration and normal platform validation;
no insecure certificate handler is provided. Configure DNS names/certificates for
separate machines. Development permits plain HTTP for local automated tests only.
Use network firewall rules to restrict service ports to trusted hosts as an
additional deployment control; the application credential checks still enforce
protection if a client reaches a service directly.
Each service requires `InternalAccess:GatewayKey`, a random credential of at least
32 characters, matched by the gateway's `Services:<service>:Key`. Services reject
missing/wrong keys and client bearer tokens. Use distinct per-service gateway keys
in deployment. The gateway forwards only its own configured key; arbitrary client
identity headers are not propagated. Do not log these headers or tokens.
Observation and Insights each have a separate `Services:ApiGateway:Key`, matched
by the gateway's `InternalAccess:Observation:Key` or `InternalAccess:Insights:Key`.
Their `X-Service-Key` authenticates an internal principal using an ASP.NET Core
handler. The Observation principal can only GET a patient profile by patient ID;
the Insights principal can only GET observation history by patient ID. Neither
can create/update/delete profiles or observations, query account associations or
call other protected routes. Both internal read paths still pass through the
gateway. Service credentials are separate from patient tokens and token keys.
Use independent random values, restrictive configuration-file permissions and
HTTPS; placeholder values in deployment examples deliberately fail validation.
## Verification
The acceptance suite exercises real HTTP hosts and PostgreSQL migrations. It covers
US-13's login, own access, missing/invalid/expired tokens, no-profile behaviour,
cross-patient reads/writes and observation ownership. Additional checks cover
caller-supplied account spoofing, persistent tokens/associations after restart,
duplicate/concurrent creation, unavailable-service recovery, direct service bypass,
internal-credential route restrictions, professional creation rejection and public
US-15 guidance. Existing functional assertions run through real token login rather
than a production authentication bypass.
Framework reference:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.bearertoken.bearertokenoptions?view=aspnetcore-10.0
## US-14 professional assignments
Predefine assignments in the gateway's external `Access:ProfessionalAssignments`
configuration, keyed by the stable professional account identifier. For example:
```json
{
"Access": {
"ProfessionalAssignments": {
"example_professional": [
"00000000-0000-0000-0000-000000000001",
"00000000-0000-0000-0000-000000000002"
]
}
}
}
```
Use actual patient identifiers returned by authenticated profile creation. The
example UUIDs are placeholders. A professional can have several patients, and
several professionals can share a patient. Duplicate identifiers are treated as
one assignment. Empty identifiers are rejected at startup. An omitted account
entry means no assignments. Configure that account's role and password hash
separately under `Authentication:Accounts`; assignments never grant a role.
`GET /api/professionals/me/patients` requires the HealthcareProfessional policy and
returns an array of `{ "patientId": "..." }` entries, in deterministic identifier
order. It lists only the caller's configured assignments, without fetching patient
records. No assignments returns `[]`. Missing profiles remain assigned identifiers;
retrieving their data follows the existing missing-resource behaviour. Caller
query parameters or identity headers cannot select another professional's list.
Patient accounts cannot use this endpoint.
Professional GET requests to existing patient profiles, observations (including
recorded legacy context), history, latest observations and numerical insight
require membership in the caller's assignment set. Observation-ID requests resolve
the actual owning patient via the protected Observation API; a supplied patient ID
is not evidence of assignment. Unassigned reads return an empty `404`, preserving
the same non-disclosure convention as patient access. Assigned missing data follows
the existing retrieval contracts. All professional POST/PUT/PATCH/DELETE requests
are rejected with `403` before ownership lookups or forwarding. There is no
assignment-management API or additional database/service.
Assignments are loaded at gateway startup, outside tokens and credential
validation. Restart the gateway after changing its external configuration. Existing
valid tokens then use the new assignment data. Empty lists need no upstream service;
observation-owner lookup failures fail closed with `502`/`504`.
The US-14 tests exercise actual login, multiple and shared assignments, empty lists,
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 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,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
</ItemGroup>
</Project>
@@ -0,0 +1,39 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using ApiGateway.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api/authentication")]
public sealed class AuthenticationController(PrototypeAccounts accounts,
IOptionsMonitor<BearerTokenOptions> options) : ControllerBase
{
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
var account = accounts.Verify(request.AccountId, request.Password);
if (account is null) return Unauthorized(new { title = "Invalid credentials." });
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, account.AccountId),
new Claim(ClaimTypes.Role, account.Role)
}, "Bearer"));
var settings = options.Get("Bearer");
var expiry = settings.TimeProvider!.GetUtcNow().Add(settings.BearerTokenExpiration);
// Use the framework's ticket protector and bearer validation. No refresh endpoint/token.
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { ExpiresUtc = expiry }, "Bearer");
Response.Headers.CacheControl = "no-store";
Response.Headers.Pragma = "no-cache";
return Ok(new { accessToken = settings.BearerTokenProtector.Protect(ticket), tokenType = "Bearer",
expiresIn = (long)settings.BearerTokenExpiration.TotalSeconds, accountId = account.AccountId, role = account.Role });
}
public sealed record LoginRequest([Required] string AccountId, [Required] string Password);
}
@@ -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);
}
}
@@ -0,0 +1,52 @@
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);
[HttpGet("patients/{patientId:guid}/trends")]
public Task GetTrend(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/trends{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);
}
}
@@ -0,0 +1,62 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[AllowAnonymous]
[Route("api/measurement-guidance")]
public sealed class MeasurementGuidanceController : ControllerBase
{
[HttpGet]
public IActionResult Get([FromQuery] string? setting, [FromQuery] string? activityCondition)
{
var requestedSetting = string.IsNullOrWhiteSpace(setting) ? "Unknown" : setting.Trim();
var requestedActivity = string.IsNullOrWhiteSpace(activityCondition) ? "Unknown" : activityCondition.Trim();
if (!new[] { "Home", "Clinic", "Other", "Unknown" }.Contains(requestedSetting, StringComparer.OrdinalIgnoreCase))
return Problem(statusCode: 400, title: "Unsupported measurement setting.");
if (!new[] { "AtRest", "DuringActivity", "AfterActivity", "Unknown" }.Contains(requestedActivity, StringComparer.OrdinalIgnoreCase))
return Problem(statusCode: 400, title: "Unsupported activity condition.");
var available = requestedSetting.Equals("Home", StringComparison.OrdinalIgnoreCase)
|| requestedSetting.Equals("Unknown", StringComparison.OrdinalIgnoreCase);
return Ok(new
{
available,
requestedSetting,
requestedActivityCondition = requestedActivity,
applicableSetting = available ? "Home" : null,
applicableActivityCondition = available ? "AtRest" : null,
reviewedOn = available ? "2026-10-04" : null,
explanation = available
? "These instructions apply to resting home self-measurement, not a clinical measurement protocol. Unknown conditions remain unknown; requesting guidance does not record a setting or certify compliance."
: "Verified guidance is unavailable for the requested setting. Home instructions have not been substituted for clinical or other-setting instructions.",
steps = available ? new[]
{
new GuidanceStep(1, "Equipment", "Use a validated upper-arm device with a cuff suited to your arm. Follow its instructions for placement and maintenance; incorrect cuff size can distort readings."),
new GuidanceStep(2, "Preparation", "Choose a quiet place. Avoid smoking for 30 minutes beforehand and rest seated for five minutes."),
new GuidanceStep(3, "Position", "Sit with back and arm supported and legs uncrossed. Put the cuff on bare skin, clear of tight clothing, and keep the arm relaxed and still during measurement."),
new GuidanceStep(4, "Measure", "Use the device as instructed. Reproduce your setting, posture and preparation when possible to help later comparisons."),
new GuidanceStep(5, "Planned monitoring", "The cited Danish home protocol uses three readings in the morning before breakfast and three in the evening before dinner, over three consecutive days. This planned series differs from saving one observation; follow individually supplied clinical instructions."),
new GuidanceStep(6, "Record", "Save actual blood-pressure values in mmHg, device-reported pulse in beats/minute, and measurement time. Record setting, activity and preparation where known, including departures from routine. Do not discard, change or invent values to fit guidance.")
} : Array.Empty<GuidanceStep>(),
pulseExplanation = available
? "Rest and activity affect the context of pulse readings. One device-reported pulse value does not assess rhythm regularity."
: null,
activityExplanation = available
? "During-activity and after-activity measurements differ from resting measurements. Record the actual conditions; do not relabel them as resting. Such observations remain valid to record."
: null,
limitations = available
? "Guidance does not guarantee accuracy or replace device or individual clinical instructions. It does not recommend medication changes. Viewing or declining it does not save or alter observations, certify a procedure, or prevent a valid submission."
: null,
sources = available ? new[]
{
new GuidanceSource("Sundhed.dk — Højt blodtryk", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/", "2024-09-25"),
new GuidanceSource("Sundhed.dk — Blodtryksmåling", "https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/undersoegelser-og-proever/kliniske-procedurer/hjertekar/blodtryksmaaling/", "2025-03-13")
} : Array.Empty<GuidanceSource>()
});
}
private sealed record GuidanceStep(int Order, string Topic, string Instruction);
private sealed record GuidanceSource(string Title, string Url, string UpdatedOn);
}
@@ -0,0 +1,81 @@
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api")]
public sealed class ObservationController(IHttpClientFactory clients) : ControllerBase
{
[HttpPost("patients/{patientId:guid}/observations")]
public Task RecordObservation(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Post, $"api/patients/{patientId}/observations", cancellationToken);
[HttpDelete("observations/{observationId:guid}")]
public Task DeleteObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Delete, $"api/observations/{observationId}", cancellationToken);
[HttpPut("observations/{observationId:guid}")]
public Task UpdateObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Put, $"api/observations/{observationId}", cancellationToken);
[HttpPatch("observations/{observationId:guid}")]
public Task PatchObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Patch, $"api/observations/{observationId}", cancellationToken);
[HttpGet("observations/{observationId:guid}")]
public Task GetObservation(Guid observationId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/observations/{observationId}", cancellationToken);
[HttpGet("patients/{patientId:guid}/observations/latest")]
public Task GetLatest(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations/latest", cancellationToken);
[HttpGet("patients/{patientId:guid}/observations")]
public Task GetByPeriod(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/observations{Request.QueryString}", cancellationToken);
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
if (method == HttpMethod.Post || method == HttpMethod.Put || method == HttpMethod.Patch)
{
request.Content = new StreamContent(Request.Body);
if (Request.ContentType is not null)
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
}
try
{
using var upstream = await clients.CreateClient("Observation")
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Response.StatusCode = (int)upstream.StatusCode;
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
foreach (var header in new[] { "X-Measurement-Setting", "X-Activity-Condition" })
if (upstream.Headers.TryGetValues(header, out var values))
Response.Headers[header] = values.ToArray();
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: "Observation service is unavailable.")
.ExecuteAsync(HttpContext);
}
}
@@ -0,0 +1,69 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api/patients")]
public sealed class PatientController(IHttpClientFactory clients) : ControllerBase
{
[HttpPost]
public Task CreatePatient(CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken);
[HttpGet("me")]
public Task GetOwnPatient(CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, "api/patients/by-account/" + Uri.EscapeDataString(User.FindFirstValue(ClaimTypes.NameIdentifier)!), cancellationToken);
[HttpGet("{patientId:guid}")]
public Task GetPatient(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken);
[HttpPut("{patientId:guid}")]
public Task UpdatePatient(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Put, $"api/patients/{patientId}", cancellationToken);
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
if (method == HttpMethod.Post)
request.Headers.Add("X-Account-Id", User.FindFirstValue(ClaimTypes.NameIdentifier));
if (method == HttpMethod.Post || method == HttpMethod.Put)
{
request.Content = new StreamContent(Request.Body);
if (Request.ContentType is not null)
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
}
try
{
using var upstream = await clients.CreateClient("PatientProfile")
.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: "Patient/Profile service is unavailable.")
.ExecuteAsync(HttpContext);
}
}
@@ -0,0 +1,17 @@
using System.Security.Claims;
using ApiGateway.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[Authorize(Policy = "HealthcareProfessional")]
[Route("api/professionals/me/patients")]
public sealed class ProfessionalController(ProfessionalAssignments assignments) : ControllerBase
{
[HttpGet]
public IActionResult GetAssignedPatients() =>
Ok(assignments.GetPatients(User.FindFirstValue(ClaimTypes.NameIdentifier)!)
.Select(patientId => new { patientId }));
}
@@ -0,0 +1,116 @@
using ApiGateway.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.DataProtection.Repositories;
namespace ApiGateway;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-api-gateway");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<PrototypeAccounts>();
builder.Services.AddSingleton<ProfessionalAssignments>();
builder.Services.AddAuthentication("ClientOrService")
.AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context =>
context.Request.Headers.ContainsKey("X-Service-Key") ? "InternalService" : "Bearer")
.AddBearerToken("Bearer", options =>
{
options.BearerTokenExpiration = TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30));
})
.AddScheme<AuthenticationSchemeOptions, InternalServiceAuthenticationHandler>("InternalService", null);
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.AddPolicy("Patient", policy => policy.RequireRole("Patient").RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
options.AddPolicy("HealthcareProfessional", policy => policy.RequireRole("HealthcareProfessional")
.RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
});
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
builder.Services.AddOptions<KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((options, configuration, logger) =>
{
var keyDirectory = configuration["Authentication:KeyDirectory"];
if (string.IsNullOrWhiteSpace(keyDirectory)) throw new InvalidOperationException("Authentication:KeyDirectory is required.");
options.XmlRepository = new FileSystemXmlRepository(new DirectoryInfo(keyDirectory), logger);
});
builder.Services.AddHttpClient("PatientProfile", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetBaseUri(configuration, "PatientProfile");
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:PatientProfile:Key"]);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddHttpClient("Observation", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetBaseUri(configuration, "Observation");
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Observation:Key"]);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
builder.Services.AddHttpClient("Insights", (services, client) =>
{
var configuration = services.GetRequiredService<IConfiguration>();
client.BaseAddress = GetBaseUri(configuration, "Insights");
client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Insights:Key"]);
})
.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");
_ = 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"]))
throw new InvalidOperationException("Authentication:KeyDirectory is required.");
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", "HealthOverview" })
if (GetBaseUri(app.Configuration, service).Scheme != "https")
throw new InvalidOperationException("Production service endpoints must use HTTPS.");
_ = app.Services.GetRequiredService<PrototypeAccounts>();
_ = app.Services.GetRequiredService<ProfessionalAssignments>();
app.UseExceptionHandler();
app.Use(async (context, next) =>
{
if (!app.Environment.IsDevelopment() && !context.Request.IsHttps) { context.Response.StatusCode = 400; return; }
await next(context);
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<PatientAccessMiddleware>();
app.MapControllers();
app.Run();
}
private static Uri GetBaseUri(IConfiguration configuration, string service)
{
var endpoint = configuration[$"Services:{service}:BaseUrl"];
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var baseUri) ||
(baseUri.Scheme != "http" && baseUri.Scheme != "https") ||
baseUri.AbsolutePath != "/" || !string.IsNullOrEmpty(baseUri.Query) ||
!string.IsNullOrEmpty(baseUri.Fragment) || !string.IsNullOrEmpty(baseUri.UserInfo))
throw new InvalidOperationException($"Services:{service}:BaseUrl must be an HTTP(S) origin URL.");
return baseUri;
}
}
@@ -0,0 +1,29 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace ApiGateway.Security;
public sealed class InternalServiceAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var supplied = Request.Headers["X-Service-Key"].ToString();
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)))
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, "Service"),
new Claim(ClaimTypes.NameIdentifier, service) }, Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name)));
}
}
return Task.FromResult(AuthenticateResult.Fail("Invalid service credential."));
}
}
@@ -0,0 +1,92 @@
using System.Net;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
namespace ApiGateway.Security;
public sealed class PatientAccessMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, IHttpClientFactory clients, IAuthorizationService authorization,
ProfessionalAssignments assignments)
{
if (context.GetEndpoint()?.Metadata.GetMetadata<IAllowAnonymous>() is not null)
{
await next(context);
return;
}
if (context.User.Identity?.IsAuthenticated != true) { context.Response.StatusCode = 401; return; }
var route = context.Request.Path.Value ?? "";
var segments = route.Trim('/').Split('/');
if (context.User.IsInRole("Service"))
{
var service = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
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;
}
var professional = (await authorization.AuthorizeAsync(context.User, "HealthcareProfessional")).Succeeded;
if (professional)
{
if (context.Request.Method != "GET") { context.Response.StatusCode = 403; return; }
if (route.Equals("/api/professionals/me/patients", StringComparison.OrdinalIgnoreCase))
{
await next(context);
return;
}
}
else if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded)
{ context.Response.StatusCode = 403; return; }
if (!professional &&
((route.Equals("/api/patients", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "POST")
|| (route.Equals("/api/patients/me", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "GET")))
{
await next(context);
return;
}
try
{
var accountId = context.User.FindFirstValue(ClaimTypes.NameIdentifier)!;
Guid? patientId = null;
if (!professional)
{
using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync(
"api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted);
if (ownResponse.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
ownResponse.EnsureSuccessStatusCode();
using var own = JsonDocument.Parse(await ownResponse.Content.ReadAsStringAsync(context.RequestAborted));
patientId = own.RootElement.GetProperty("patientId").GetGuid();
}
Guid requestedPatient;
if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
&& Guid.TryParse(segments[2], out requestedPatient)) { }
else if (segments.Length == 3 && segments[0] == "api" && segments[1] == "observations"
&& Guid.TryParse(segments[2], out var observationId))
{
using var response = await clients.CreateClient("Observation").GetAsync($"api/observations/{observationId}", context.RequestAborted);
if (response.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; }
response.EnsureSuccessStatusCode();
using var observation = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.RequestAborted));
requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid();
}
else { context.Response.StatusCode = 404; return; }
var permitted = professional ? assignments.IsAssigned(accountId, requestedPatient) : requestedPatient == patientId;
if (!permitted) { context.Response.StatusCode = 404; return; }
await next(context);
}
catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); }
catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested)
{ await Results.Problem(statusCode: 504, title: "Ownership lookup timed out.").ExecuteAsync(context); }
}
}
@@ -0,0 +1,24 @@
namespace ApiGateway.Security;
// Application access data, separate from credentials and token contents.
public sealed class ProfessionalAssignments
{
private readonly Dictionary<string, Guid[]> assignments;
public ProfessionalAssignments(IConfiguration configuration)
{
assignments = configuration.GetSection("Access:ProfessionalAssignments")
.Get<Dictionary<string, Guid[]>>() ?? new(StringComparer.Ordinal);
foreach (var accountId in assignments.Keys.ToArray())
{
if (string.IsNullOrWhiteSpace(accountId) || assignments[accountId].Any(id => id == Guid.Empty))
throw new InvalidOperationException("Professional assignments require an account identifier and nonempty patient identifiers.");
assignments[accountId] = assignments[accountId].Distinct().Order().ToArray();
}
}
public IReadOnlyList<Guid> GetPatients(string accountId) =>
assignments.TryGetValue(accountId, out var patients) ? Array.AsReadOnly(patients) : Array.Empty<Guid>();
public bool IsAssigned(string accountId, Guid patientId) => GetPatients(accountId).Contains(patientId);
}
@@ -0,0 +1,39 @@
using Microsoft.AspNetCore.Identity;
namespace ApiGateway.Security;
public sealed class PrototypeAccount
{
public string AccountId { get; set; } = "";
public string Role { get; set; } = "Patient";
public string PasswordHash { get; set; } = "";
}
public sealed class PrototypeAccounts
{
private readonly Dictionary<string, PrototypeAccount> accounts;
private readonly PasswordHasher<PrototypeAccount> hasher = new();
private readonly PrototypeAccount dummy = new() { AccountId = "invalid" };
public PrototypeAccounts(IConfiguration configuration)
{
var configured = configuration.GetSection("Authentication:Accounts").Get<PrototypeAccount[]>() ?? [];
if (configured.Length == 0 || configured.Any(a => string.IsNullOrWhiteSpace(a.AccountId) || a.AccountId.Length > 128 || a.AccountId.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_')) || string.IsNullOrWhiteSpace(a.PasswordHash)
|| a.Role is not ("Patient" or "HealthcareProfessional")))
throw new InvalidOperationException("Authentication accounts require an identifier, password hash and supported role.");
accounts = configured.ToDictionary(a => a.AccountId, StringComparer.Ordinal);
dummy.PasswordHash = hasher.HashPassword(dummy, Guid.NewGuid().ToString());
}
public PrototypeAccount? Verify(string accountId, string password)
{
var known = accounts.TryGetValue(accountId, out var account);
account ??= dummy;
try
{
var result = hasher.VerifyHashedPassword(account, account.PasswordHash, password);
return known && result != PasswordVerificationResult.Failed ? account : null;
}
catch (FormatException) { return null; }
}
}
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
@@ -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,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
</ItemGroup>
</Project>
@@ -0,0 +1,79 @@
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.Host.UseWindowsService(options => options.ServiceName = "healthapp-health-overview");
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,36 @@
using System.ComponentModel.DataAnnotations;
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,
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 history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
return calculator.CalculateSummary(patientId, from, to, history, selection);
}
public async Task<TrendAssessment> GetTrendAsync(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 history = await observations.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
return calculator.CalculateTrend(patientId, from, to, history, selection);
}
private static DateTime NormalizeTimestamp(DateTime value) =>
DateTime.SpecifyKind(value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(),
DateTimeKind.Unspecified);
}
@@ -0,0 +1,23 @@
using InsightsService.Domain;
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,
ContextSelection selection, CancellationToken cancellationToken)
{
var start = Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture));
var end = Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture));
var filters = "";
if (selection.Setting is not null) filters += "&setting=" + Uri.EscapeDataString(selection.Setting);
if (selection.ActivityCondition is not null) filters += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition);
using var response = await client.GetAsync($"api/patients/{patientId}/observations?from={start}&to={end}{filters}",
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<List<ObservationDto>>(cancellationToken)
?? throw new HttpRequestException("Observation history response was empty.");
}
}
@@ -0,0 +1,10 @@
using InsightsService.Domain;
using InsightsService.Contracts;
namespace InsightsService.Clients;
public interface ObservationServiceClient
{
Task<List<ObservationDto>> GetByPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken);
}
@@ -0,0 +1,8 @@
using InsightsService.Domain;
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,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
@@ -0,0 +1,8 @@
namespace InsightsService.Contracts;
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, MeasurementContextDto? MeasurementContext = null,
string? Context = null, string? Note = null);
public sealed record MeasurementContextDto(string? Setting, string? ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
@@ -0,0 +1,74 @@
using InsightsService.Domain;
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,
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
var insight = await service.GetSummaryAsync(patientId, from, to, selection, 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,
insight.AppliedSelection, insight.ContributingCount, insight.ContextExplanation));
}
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.");
}
}
[HttpGet("/api/patients/{patientId:guid}/trends")]
public async Task<ActionResult<TrendAssessment>> GetTrend(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
return Ok(await service.GetTrendAsync(patientId, from, to, selection, cancellationToken));
}
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,12 @@
using System.ComponentModel.DataAnnotations;
namespace InsightsService.Domain;
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; }
}
@@ -0,0 +1,6 @@
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,
ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation);
@@ -0,0 +1,223 @@
using System.Globalization;
using InsightsService.Contracts;
namespace InsightsService.Domain;
public sealed partial class InsightCalculator
{
private const string GeneralLimits = "General reference thresholds are not individual treatment targets. " +
"This is a descriptive assessment, not a diagnosis or medication recommendation. " +
"Symptoms, treatment, training, risk factors and measurement technique are not established by these observations.";
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{
var comparability = AssessComparability(observations);
return new(patientId, from, to, selection, observations.Count, comparability,
AssessMeasurement("Systolic", "mmHg", observations, o => o.Systolic, comparability),
AssessMeasurement("Diastolic", "mmHg", observations, o => o.Diastolic, comparability),
AssessMeasurement("Pulse", "beats/min", observations, o => o.Pulse, comparability));
}
private static MeasurementAssessment AssessMeasurement(string metric, string unit,
IReadOnlyList<ObservationDto> observations, Func<ObservationDto, int> value,
ComparabilityAssessment comparability)
{
if (observations.Count == 0)
return new(metric, unit, null, null, null, null, 0, "Unavailable", "Unavailable", null, 0,
null, "No matching observations; insufficient observation data for trend calculation.",
null, "Unavailable: no matching observations.", "CannotInterpret", GeneralLimits);
// Collapse timestamp ties for temporal calculations only; descriptive levels retain every observation.
var points = observations.GroupBy(o => o.MeasuredAt).OrderBy(g => g.Key)
.Select(g => (Time: g.Key, Value: g.Average(o => (decimal)value(o)))).ToArray();
var minimum = observations.Min(value);
var maximum = observations.Max(value);
var mean = observations.Average(o => (decimal)value(o));
var signs = points.Zip(points.Skip(1), (a, b) => Math.Sign(b.Value - a.Value))
.Where(s => s != 0).ToArray();
var reversals = signs.Zip(signs.Skip(1), (a, b) => a != b ? 1 : 0).Sum();
var direction = points.Length < 2 ? "Unavailable" : signs.Length == 0 ? "NoClearDirection" :
reversals > 0 ? "Mixed" : signs[0] > 0 ? "Increasing" : "Decreasing";
decimal? slope = null;
var overall = "Unavailable";
decimal? totalChange = null;
if (points.Length >= 2)
{
// Scale time to [0,1] before OLS, avoiding extreme timestamp magnitudes.
var span = (decimal)(points[^1].Time.Ticks - points[0].Time.Ticks);
var xs = points.Select(p => (p.Time.Ticks - points[0].Time.Ticks) / span).ToArray();
var xMean = xs.Average();
var yMean = points.Average(p => p.Value);
var numerator = points.Select((p, i) => (xs[i] - xMean) * (p.Value - yMean)).Sum();
var denominator = xs.Sum(x => (x - xMean) * (x - xMean));
var scaledSlope = numerator / denominator;
slope = scaledSlope / (span / TimeSpan.TicksPerDay);
overall = scaledSlope > 0 ? "Increasing" : scaledSlope < 0 ? "Decreasing" : "NoClearDirection";
totalChange = points.Zip(points.Skip(1), (a, b) => Math.Abs(b.Value - a.Value)).Sum();
}
var numerical = $"All {observations.Count} observations: mean {Format(mean)}, minimum {minimum}, maximum {maximum}, " +
$"range {maximum - minimum} {unit}. " + (points.Length < 2
? "Direction is unavailable: at least two distinct measurement timestamps are required."
: $"Temporal direction: {direction}; full-period least-squares direction: {overall}; " +
$"{reversals} reversal(s). Timestamp ties use arithmetic means. " +
$"Total successive change is {Format(totalChange!.Value)} {unit}.") +
" Range and successive change describe observed variation; no clinical stability classification is made.";
var reference = SelectReference(metric, observations, comparability);
var comparison = "Unavailable: known, non-conflicting resting conditions" +
(metric == "Pulse" ? "" : " and a single Home or Clinic setting") + " are required; recorded inadequate preparation also limits applicability.";
var interpretation = "CannotInterpret";
var hint = "Numerical changes alone do not establish favourable or concerning development.";
if (reference is not null)
{
var above = observations.Count(o => IsHigh(value(o), reference));
var below = observations.Count(o => IsLow(value(o), reference));
comparison = $"Descriptive mean {Format(mean)} {unit}; {above} observation(s) " +
$"{reference.UpperComparison} {Format(reference.UpperBoundary)} {unit}" +
(reference.LowerBoundary is { } lower ? $"; {below} observation(s) < {Format(lower)} {unit}." : ".") +
" This period does not establish a guideline diagnostic measurement protocol. " + reference.Limitation;
if (points.Length >= 2 && comparability.Status == "SupportedRecordedComparability")
{
var first = points[0].Value;
var last = points[^1].Value;
if (reversals > 0 && (above > 0 || below > 0))
{
interpretation = "Mixed";
hint = "Reversing movements and excursions outside the cited reference boundaries coexist; " +
"an overall slope does not establish consistent improvement or deterioration.";
}
else if (direction == "Decreasing" && IsHigh(first, reference) &&
!IsLow(last, reference) && below == 0 && (metric == "Pulse" || IsHigh(last, reference)))
{
interpretation = "PotentiallyFavourable";
hint = "Movement away from initially high levels towards the cited reference boundary may be favourable. " +
"This is a cautious inference from the source's reference comparison, not a clinical decision rule. " +
(IsHigh(last, reference) ? "The latest timestamp mean remains above or at the high boundary." :
"Reaching the reference interval does not establish an individual treatment target or good health.");
}
else if (metric == "Pulse" && direction == "Increasing" && IsLow(first, reference) &&
!IsHigh(last, reference) && above == 0)
{
interpretation = "PotentiallyFavourable";
hint = "Movement away from initially low resting pulse towards the reference interval may be favourable, " +
"but low pulse may be physiological in trained people. This is a cautious inference, not a clinical rule. " +
(IsLow(last, reference) ? "The latest timestamp mean remains below the lower boundary." :
"Being within these boundaries does not establish good health.");
}
else if (above > 0 || below > 0)
{
interpretation = "PotentiallyConcerning";
hint = "Observed levels outside the cited reference boundaries may warrant clinical review. " +
"Limited variation does not establish healthy levels, and a decrease into low resting pulse " +
"is not automatically favourable. The cause and individual significance cannot be determined here.";
}
}
else
hint = "The recorded context supports this limited reference comparison, but " +
(points.Length < 2 ? "temporal direction is unavailable. " :
"missing or differing conditions limit interpretation of the combined trajectory. ") +
"An outside-reference value is not dismissed because preparation information is incomplete.";
}
return new(metric, unit, Round(mean), minimum, maximum, maximum - minimum, points.Length,
direction, overall, slope is { } s ? Math.Round(s, 6, MidpointRounding.AwayFromZero) : null,
reversals, totalChange is { } change ? Round(change) : null, numerical, reference,
comparison, interpretation, hint + " " + comparability.Explanation + " " + GeneralLimits);
}
private static ClinicalReference? SelectReference(string metric, IReadOnlyList<ObservationDto> observations,
ComparabilityAssessment comparability)
{
if (comparability.Conflicts.Count > 0 ||
observations.Any(o => o.MeasurementContext?.ActivityCondition != "AtRest")) return null;
if (metric == "Pulse")
return new("Recorded resting pulse", 50, "<", 100, ">",
[new("Patienthåndbogen: Bradykardi (langsom puls)",
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/",
"2025-09-02", "2026-10-05"),
new("Patienthåndbogen: Hurtig puls (takykardi)",
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/",
"2025-05-12", "2026-10-05")],
"These are resting-rate reference boundaries, not a diagnosis, a universal normal range or a treatment target. " +
"Low pulse can be physiological in trained people; age, fitness, symptoms and medicines affect applicability.");
var settings = observations.Select(o => o.MeasurementContext?.Setting).Distinct().ToArray();
if (settings.Length != 1 || settings[0] is not ("Home" or "Clinic")) return null;
// Known inadequate rest prevents even a provisional resting-pressure comparison.
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5)) return null;
if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
!new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
return null;
var threshold = metric == "Systolic" ? (settings[0] == "Home" ? 135 : 140) :
(settings[0] == "Home" ? 85 : 90);
return new($"Recorded {settings[0]} resting blood pressure", null, null, threshold, ">=",
[new("Lægehåndbogen: Højt blodtryk",
"https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/",
"2024-09-25", "2026-10-05")],
"Setting-specific high-pressure reference threshold. Missing preparation details make this comparison provisional; " +
"five minutes of rest, appropriate technique and repeated measurements are not inferred. " +
"Being below a high-pressure threshold does not establish an appropriate lower level or a personalised goal.");
}
private static bool IsHigh(decimal value, ClinicalReference reference) =>
reference.UpperComparison == ">=" ? value >= reference.UpperBoundary : value > reference.UpperBoundary;
private static bool IsLow(decimal value, ClinicalReference reference) =>
reference.LowerBoundary is { } lower && value < lower;
private static decimal Round(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
private static string Format(decimal value) => Round(value).ToString("0.##", CultureInfo.InvariantCulture);
private static ComparabilityAssessment AssessComparability(IReadOnlyList<ObservationDto> observations)
{
List<string> similarities = [], differences = [], missing = [], conflicts = [];
if (observations.Count == 0)
return new("InsufficientContext", similarities, differences, missing, conflicts,
"No matching observations are available to assess comparability.");
var details = new (string Name, string?[] Values)[]
{
("setting", observations.Select(o => o.MeasurementContext?.Setting).ToArray()),
("activity condition", observations.Select(o => o.MeasurementContext?.ActivityCondition).ToArray()),
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray())
};
foreach (var (name, values) in details)
{
var known = values.Where(v => !string.IsNullOrWhiteSpace(v) && v != "Unknown")
.Select(v => v!.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
if (values.Any(v => string.IsNullOrWhiteSpace(v) || v == "Unknown")) missing.Add(name);
if (known.Length > 1) differences.Add($"{name}: {string.Join(" / ", known)}");
else if (known.Length == 1 && !missing.Contains(name)) similarities.Add($"{name}: {known[0]}");
}
var circumstances = observations.Select(o => o.MeasurementContext?.AdditionalCircumstances)
.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s!.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToArray();
if (circumstances.Length > 1) differences.Add("additional circumstances differ");
if (observations.Any(o => o.MeasurementContext?.RestDurationMinutes is < 5))
differences.Add("recorded rest duration is below the five-minute blood-pressure preparation recommendation");
foreach (var observation in observations)
{
var context = observation.MeasurementContext;
var narrative = string.Join(" ", observation.Context, observation.Note, context?.AdditionalCircumstances,
context?.BodyPosition, context?.DeviceDetails, context?.CuffDetails).ToLowerInvariant();
if (context?.ActivityCondition == "AtRest" && new[]
{ "during exercise", "during activity", "after exercise", "after activity", "under motion", "under træning", "efter motion", "efter træning" }
.Any(narrative.Contains)) conflicts.Add("AtRest conflicts with an activity description in recorded text.");
if (context?.Setting == "Home" && new[] { "at clinic", "in clinic", "at the clinic", "på klinik", "hos lægen" }.Any(narrative.Contains))
conflicts.Add("Home conflicts with a clinic description in recorded text.");
if (context?.Setting == "Clinic" && new[] { "at home", "hjemme" }.Any(narrative.Contains))
conflicts.Add("Clinic conflicts with a home description in recorded text.");
}
var status = conflicts.Count > 0 ? "ConflictingContext" : differences.Count > 0 ? "KnownDifferences" :
missing.Count > 0 ? "InsufficientContext" : "SupportedRecordedComparability";
var explanation = $"Recorded comparability: {status}. " +
(missing.Count > 0 ? $"Unknown or missing: {string.Join(", ", missing)}. " : "") +
(differences.Count > 0 ? $"Known differences: {string.Join("; ", differences)}. " : "") +
(conflicts.Count > 0 ? $"Conflicts: {string.Join("; ", conflicts.Distinct())} " : "") +
"Matching recorded details support comparability only of those details; they do not certify identical " +
"conditions, validated equipment or guideline-compliant technique. Narrative conflict detection is limited " +
"to documented phrases; other text is not proof of comparability. A difference between Home and Clinic " +
"selections alone is not improvement or deterioration over time.";
return new(status, similarities, differences, missing, conflicts.Distinct().Order(StringComparer.Ordinal).ToArray(), explanation);
}
}
@@ -0,0 +1,50 @@
using System.Globalization;
using InsightsService.Contracts;
namespace InsightsService.Domain;
public sealed partial class InsightCalculator
{
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to,
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
{
if (observations.Count == 0)
return null;
return new HealthInsight(patientId, from, to,
Math.Round(observations.Average(o => (decimal)o.Systolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Diastolic), 2, MidpointRounding.AwayFromZero),
Math.Round(observations.Average(o => (decimal)o.Pulse), 2, MidpointRounding.AwayFromZero),
observations.Min(o => o.Systolic), observations.Max(o => o.Systolic),
observations.Min(o => o.Diastolic), observations.Max(o => o.Diastolic),
selection, observations.Count, DescribeContext(observations));
}
private static string DescribeContext(IReadOnlyList<ObservationDto> observations)
{
var settings = observations.Select(o => o.MeasurementContext?.Setting ?? "Unknown").ToArray();
var activities = observations.Select(o => o.MeasurementContext?.ActivityCondition ?? "Unknown").ToArray();
var explanation = $"Recorded settings: {Counts(settings)}. Recorded activity conditions: {Counts(activities)}.";
if (settings.Distinct().Count() > 1 || activities.Distinct().Count() > 1)
explanation += " This numerical summary pools mixed settings or activity conditions.";
if (settings.Contains("Unknown") || activities.Contains("Unknown"))
explanation += " Some setting or activity information is unknown.";
var details = new (string Name, string?[] Values)[]
{
("rest duration", observations.Select(o => o.MeasurementContext?.RestDurationMinutes?.ToString("G29", CultureInfo.InvariantCulture)).ToArray()),
("body position", observations.Select(o => o.MeasurementContext?.BodyPosition).ToArray()),
("measured arm", observations.Select(o => o.MeasurementContext?.MeasuredArm).ToArray()),
("device", observations.Select(o => o.MeasurementContext?.DeviceDetails).ToArray()),
("cuff", observations.Select(o => o.MeasurementContext?.CuffDetails).ToArray()),
("additional circumstances", observations.Select(o => o.MeasurementContext?.AdditionalCircumstances).ToArray())
};
var missing = details.Where(d => d.Values.Any(string.IsNullOrWhiteSpace)).Select(d => d.Name).ToArray();
var differing = details.Where(d => d.Values.Where(v => !string.IsNullOrWhiteSpace(v)).Distinct().Count() > 1)
.Select(d => d.Name).ToArray();
if (missing.Length > 0) explanation += $" Optional details are unrecorded for some observations: {string.Join(", ", missing)}.";
if (differing.Length > 0) explanation += $" Recorded detail values differ: {string.Join(", ", differing)}.";
return explanation + " These are descriptive statistics, not a diagnostic monitoring protocol; recorded categories alone do not establish clinically comparable conditions. Legacy narrative text does not establish a category.";
}
private static string Counts(IEnumerable<string> values) => string.Join(", ", values.GroupBy(v => v)
.OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => $"{g.Key} ({g.Count()})"));
}
@@ -0,0 +1,21 @@
namespace InsightsService.Domain;
public sealed record TrendAssessment(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
ContextSelection AppliedSelection, int ContributingCount, ComparabilityAssessment Comparability,
MeasurementAssessment Systolic, MeasurementAssessment Diastolic, MeasurementAssessment Pulse);
public sealed record ComparabilityAssessment(string Status, IReadOnlyList<string> KnownSimilarities,
IReadOnlyList<string> KnownDifferences, IReadOnlyList<string> MissingDetails,
IReadOnlyList<string> Conflicts, string Explanation);
public sealed record MeasurementAssessment(string Metric, string Unit, decimal? Mean, int? Minimum,
int? Maximum, int? Range, int DistinctTimestampCount, string Direction, string OverallDirection,
decimal? SlopePerDay, int ReversalCount, decimal? TotalSuccessiveChange,
string NumericalExplanation, ClinicalReference? Reference, string ReferenceComparison,
string Interpretation, string Hint);
public sealed record ClinicalReference(string Scope, decimal? LowerBoundary, string? LowerComparison,
decimal UpperBoundary, string UpperComparison, IReadOnlyList<ReferenceSource> Sources,
string Limitation);
public sealed record ReferenceSource(string Title, string Url, string Updated, string Reviewed);
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
</ItemGroup>
</Project>
@@ -0,0 +1,61 @@
using System.Security.Cryptography;
using System.Text;
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.Host.UseWindowsService(options => options.ServiceName = "healthapp-insights");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddScoped<InsightsApplicationService>();
builder.Services.AddSingleton<InsightCalculator>();
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 });
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"
}
}
}
+64
View File
@@ -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.
@@ -0,0 +1,89 @@
using System.ComponentModel.DataAnnotations;
using System.Net;
using ObservationService.Contracts;
using ObservationService.Domain;
namespace ObservationService.Application;
public sealed class ObservationApplicationService(ObservationRepository repository, IHttpClientFactory clients)
{
public Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken) =>
repository.DeleteAsync(observationId, cancellationToken);
public Task<BloodPressureObservation?> UpdateAsync(Guid observationId, UpdateObservationRequest request,
CancellationToken cancellationToken)
{
if (request.Systolic is null or <= 0 || request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
throw new ArgumentException("Positive measured values are required.", nameof(request));
return PatchAsync(observationId, new PatchObservationRequest { Systolic = request.Systolic, Diastolic = request.Diastolic, Pulse = request.Pulse }, cancellationToken);
}
public Task<BloodPressureObservation?> PatchAsync(Guid observationId, PatchObservationRequest request,
CancellationToken cancellationToken)
{
Validator.ValidateObject(request, new ValidationContext(request), validateAllProperties: true);
if (request.MeasurementContext is not null)
Validator.ValidateObject(request.MeasurementContext, new ValidationContext(request.MeasurementContext), validateAllProperties: true);
return repository.UpdateAsync(observationId, request, DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified), cancellationToken);
}
public async Task<BloodPressureObservation?> RecordAsync(Guid patientId, RecordObservationRequest request,
CancellationToken cancellationToken)
{
if (request.MeasuredAt is null || request.Systolic is null or <= 0 ||
request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
throw new ArgumentException("A timestamp and positive measured values are required.", nameof(request));
var suppliedContext = request.MeasurementContext ?? new MeasurementContext();
var measurementContext = suppliedContext with
{
Setting = suppliedContext.Setting ?? "Unknown",
ActivityCondition = suppliedContext.ActivityCondition ?? "Unknown"
};
Validator.ValidateObject(measurementContext, new ValidationContext(measurementContext), validateAllProperties: true);
using var patient = await clients.CreateClient("ApiGateway").GetAsync($"api/patients/{patientId}",
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (patient.StatusCode == HttpStatusCode.NotFound)
return null;
// Upstream failures must never be interpreted as an existing patient.
patient.EnsureSuccessStatusCode();
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
var measuredAt = request.MeasuredAt.Value;
if (measuredAt.Kind != DateTimeKind.Unspecified)
measuredAt = measuredAt.ToUniversalTime();
return await repository.SaveAsync(new BloodPressureObservation
{
ObservationId = Guid.NewGuid(), PatientId = patientId,
MeasuredAt = DateTime.SpecifyKind(measuredAt, DateTimeKind.Unspecified),
Systolic = request.Systolic.Value, Diastolic = request.Diastolic.Value,
Pulse = request.Pulse.Value, Context = request.Context, Note = request.Note,
MeasurementContext = measurementContext,
CreatedAt = now, UpdatedAt = now
}, cancellationToken);
}
public Task<BloodPressureObservation?> GetByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
repository.FindByIdAsync(observationId, cancellationToken);
public Task<BloodPressureObservation?> GetLatestAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindLatestByPatientIdAsync(patientId, cancellationToken);
public Task<List<BloodPressureObservation>> GetByPeriodAsync(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);
return repository.FindByPatientIdAndPeriodAsync(patientId, from, to, selection, cancellationToken);
}
private static DateTime NormalizeTimestamp(DateTime timestamp) =>
DateTime.SpecifyKind(timestamp.Kind == DateTimeKind.Unspecified ? timestamp : timestamp.ToUniversalTime(),
DateTimeKind.Unspecified);
}
@@ -0,0 +1,16 @@
using ObservationService.Contracts;
using ObservationService.Domain;
namespace ObservationService.Application;
public interface ObservationRepository
{
Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken);
Task<BloodPressureObservation?> UpdateAsync(Guid observationId, PatchObservationRequest request,
DateTime updatedAt, CancellationToken cancellationToken);
Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken);
Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken);
Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken);
}
@@ -0,0 +1,87 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace ObservationService.Contracts;
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record MeasurementContextPatch
{
private string? setting;
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting
{
get => setting;
init { setting = value; SettingSpecified = true; }
}
[JsonIgnore]
public bool SettingSpecified { get; private set; }
private string? activityCondition;
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition
{
get => activityCondition;
init { activityCondition = value; ActivityConditionSpecified = true; }
}
[JsonIgnore]
public bool ActivityConditionSpecified { get; private set; }
private decimal? restDurationMinutes;
[Range(0, double.MaxValue)]
public decimal? RestDurationMinutes
{
get => restDurationMinutes;
init { restDurationMinutes = value; RestDurationMinutesSpecified = true; }
}
[JsonIgnore]
public bool RestDurationMinutesSpecified { get; private set; }
private string? bodyPosition;
public string? BodyPosition
{
get => bodyPosition;
init { bodyPosition = value; BodyPositionSpecified = true; }
}
[JsonIgnore]
public bool BodyPositionSpecified { get; private set; }
private string? measuredArm;
public string? MeasuredArm
{
get => measuredArm;
init { measuredArm = value; MeasuredArmSpecified = true; }
}
[JsonIgnore]
public bool MeasuredArmSpecified { get; private set; }
private string? deviceDetails;
public string? DeviceDetails
{
get => deviceDetails;
init { deviceDetails = value; DeviceDetailsSpecified = true; }
}
[JsonIgnore]
public bool DeviceDetailsSpecified { get; private set; }
private string? cuffDetails;
public string? CuffDetails
{
get => cuffDetails;
init { cuffDetails = value; CuffDetailsSpecified = true; }
}
[JsonIgnore]
public bool CuffDetailsSpecified { get; private set; }
private string? additionalCircumstances;
public string? AdditionalCircumstances
{
get => additionalCircumstances;
init { additionalCircumstances = value; AdditionalCircumstancesSpecified = true; }
}
[JsonIgnore]
public bool AdditionalCircumstancesSpecified { get; private set; }
[JsonIgnore]
public bool HasChanges => SettingSpecified || ActivityConditionSpecified || RestDurationMinutesSpecified ||
BodyPositionSpecified || MeasuredArmSpecified || DeviceDetailsSpecified || CuffDetailsSpecified || AdditionalCircumstancesSpecified;
}
@@ -0,0 +1,6 @@
using ObservationService.Domain;
namespace ObservationService.Contracts;
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, MeasurementContext MeasurementContext);
@@ -0,0 +1,78 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace ObservationService.Contracts;
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record PatchObservationRequest : IValidatableObject
{
private int? systolic;
[Range(1, int.MaxValue)]
public int? Systolic
{
get => systolic;
init { systolic = value; SystolicSpecified = true; }
}
[JsonIgnore]
public bool SystolicSpecified { get; private set; }
private int? diastolic;
[Range(1, int.MaxValue)]
public int? Diastolic
{
get => diastolic;
init { diastolic = value; DiastolicSpecified = true; }
}
[JsonIgnore]
public bool DiastolicSpecified { get; private set; }
private int? pulse;
[Range(1, int.MaxValue)]
public int? Pulse
{
get => pulse;
init { pulse = value; PulseSpecified = true; }
}
[JsonIgnore]
public bool PulseSpecified { get; private set; }
private MeasurementContextPatch? measurementContext;
public MeasurementContextPatch? MeasurementContext
{
get => measurementContext;
init { measurementContext = value; MeasurementContextSpecified = true; }
}
[JsonIgnore]
public bool MeasurementContextSpecified { get; private set; }
private string? context;
public string? Context
{
get => context;
init { context = value; ContextSpecified = true; }
}
[JsonIgnore]
public bool ContextSpecified { get; private set; }
private string? note;
public string? Note
{
get => note;
init { note = value; NoteSpecified = true; }
}
[JsonIgnore]
public bool NoteSpecified { get; private set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (SystolicSpecified && Systolic is null)
yield return new ValidationResult("Systolic cannot be cleared.", [nameof(Systolic)]);
if (DiastolicSpecified && Diastolic is null)
yield return new ValidationResult("Diastolic cannot be cleared.", [nameof(Diastolic)]);
if (PulseSpecified && Pulse is null)
yield return new ValidationResult("Pulse cannot be cleared.", [nameof(Pulse)]);
if (!SystolicSpecified && !DiastolicSpecified && !PulseSpecified && !ContextSpecified && !NoteSpecified &&
!(MeasurementContextSpecified && (MeasurementContext is null || MeasurementContext.HasChanges)))
yield return new ValidationResult("Supply at least one supported field to update.");
}
}
@@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations;
using ObservationService.Domain;
namespace ObservationService.Contracts;
public sealed record RecordObservationRequest
{
[Required]
public DateTime? MeasuredAt { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Systolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Diastolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Pulse { get; init; }
public MeasurementContext? MeasurementContext { get; init; }
public string? Context { get; init; }
public string? Note { get; init; }
}
@@ -0,0 +1,17 @@
using System.Text.Json.Serialization;
using System.ComponentModel.DataAnnotations;
namespace ObservationService.Contracts;
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public sealed record UpdateObservationRequest
{
[Required, Range(1, int.MaxValue)]
public int? Systolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Diastolic { get; init; }
[Required, Range(1, int.MaxValue)]
public int? Pulse { get; init; }
}
@@ -0,0 +1,90 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using ObservationService.Application;
using ObservationService.Contracts;
using ObservationService.Domain;
namespace ObservationService.Controllers;
[ApiController]
[Route("api")]
public sealed class ObservationController(ObservationApplicationService service) : ControllerBase
{
[HttpPost("patients/{patientId:guid}/observations")]
public async Task<ActionResult<ObservationDto>> RecordObservation(Guid patientId, RecordObservationRequest request,
CancellationToken cancellationToken)
{
try
{
var observation = await service.RecordAsync(patientId, request, cancellationToken);
return observation is null
? NotFound()
: CreatedAtAction(nameof(GetObservation), new { observationId = observation.ObservationId }, ToDto(observation));
}
catch (HttpRequestException)
{
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Patient lookup is unavailable.");
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Patient lookup timed out.");
}
}
[HttpDelete("observations/{observationId:guid}")]
public async Task<IActionResult> DeleteObservation(Guid observationId, CancellationToken cancellationToken) =>
await service.DeleteAsync(observationId, cancellationToken) ? NoContent() : NotFound();
[HttpPut("observations/{observationId:guid}")]
public async Task<ActionResult<ObservationDto>> UpdateObservation(Guid observationId, UpdateObservationRequest request,
CancellationToken cancellationToken)
{
var observation = await service.UpdateAsync(observationId, request, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpPatch("observations/{observationId:guid}")]
public async Task<ActionResult<ObservationDto>> PatchObservation(Guid observationId, PatchObservationRequest request,
CancellationToken cancellationToken)
{
var observation = await service.PatchAsync(observationId, request, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpGet("observations/{observationId:guid}")]
public async Task<ActionResult<ObservationDto>> GetObservation(Guid observationId, CancellationToken cancellationToken)
{
var observation = await service.GetByIdAsync(observationId, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpGet("patients/{patientId:guid}/observations/latest")]
public async Task<ActionResult<ObservationDto>> GetLatest(Guid patientId, CancellationToken cancellationToken)
{
var observation = await service.GetLatestAsync(patientId, cancellationToken);
return observation is null ? NotFound() : Ok(ToDto(observation));
}
[HttpGet("patients/{patientId:guid}/observations")]
public async Task<ActionResult<List<ObservationDto>>> GetByPeriod(Guid patientId,
[FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to,
[FromQuery] ContextSelection selection, CancellationToken cancellationToken)
{
try
{
var observations = await service.GetByPeriodAsync(patientId, from, to, selection, cancellationToken);
Response.Headers["X-Measurement-Setting"] = selection.Setting ?? "All";
Response.Headers["X-Activity-Condition"] = selection.ActivityCondition ?? "All";
return Ok(observations.Select(ToDto).ToList());
}
catch (ArgumentException)
{
ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time.");
return ValidationProblem(ModelState);
}
}
private static ObservationDto ToDto(BloodPressureObservation observation) =>
new(observation.ObservationId, observation.PatientId, observation.MeasuredAt, observation.Systolic,
observation.Diastolic, observation.Pulse, observation.Context, observation.Note, observation.MeasurementContext);
}
@@ -0,0 +1,16 @@
namespace ObservationService.Domain;
public sealed class BloodPressureObservation
{
public Guid ObservationId { get; set; }
public Guid PatientId { get; set; }
public DateTime MeasuredAt { get; set; }
public int Systolic { get; set; }
public int Diastolic { get; set; }
public int Pulse { get; set; }
public MeasurementContext MeasurementContext { get; set; } = new();
public string? Context { get; set; }
public string? Note { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace ObservationService.Domain;
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; }
}
@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
namespace ObservationService.Domain;
public sealed record MeasurementContext
{
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
public string? Setting { get; init; } = "Unknown";
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
public string? ActivityCondition { get; init; } = "Unknown";
[Range(0, double.MaxValue)]
public decimal? RestDurationMinutes { get; init; }
public string? BodyPosition { get; init; }
public string? MeasuredArm { get; init; }
public string? DeviceDetails { get; init; }
public string? CuffDetails { get; init; }
public string? AdditionalCircumstances { get; init; }
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
</ItemGroup>
</Project>
@@ -0,0 +1,77 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using ObservationService.Persistence;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
[DbContext(typeof(ObservationDbContext))]
[Migration("20261001095222_InitialObservationSchema")]
partial class InitialObservationSchema
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.Property<Guid>("ObservationId")
.HasColumnType("uuid")
.HasColumnName("observation_id");
b.Property<string>("Context")
.HasColumnType("character varying")
.HasColumnName("context");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<int>("Diastolic")
.HasColumnType("integer")
.HasColumnName("diastolic");
b.Property<DateTime>("MeasuredAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("measured_at");
b.Property<string>("Note")
.HasColumnType("character varying")
.HasColumnName("note");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<int>("Pulse")
.HasColumnType("integer")
.HasColumnName("pulse");
b.Property<int>("Systolic")
.HasColumnType("integer")
.HasColumnName("systolic");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("ObservationId");
b.ToTable("blood_pressure_observation", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,42 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
/// <inheritdoc />
public partial class InitialObservationSchema : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "blood_pressure_observation",
columns: table => new
{
observation_id = table.Column<Guid>(type: "uuid", nullable: false),
patient_id = table.Column<Guid>(type: "uuid", nullable: false),
measured_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
systolic = table.Column<int>(type: "integer", nullable: false),
diastolic = table.Column<int>(type: "integer", nullable: false),
pulse = table.Column<int>(type: "integer", nullable: false),
context = table.Column<string>(type: "character varying", nullable: true),
note = table.Column<string>(type: "character varying", nullable: true),
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_blood_pressure_observation", x => x.observation_id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "blood_pressure_observation");
}
}
}
@@ -0,0 +1,134 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using ObservationService.Persistence;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
[DbContext(typeof(ObservationDbContext))]
[Migration("20261005094632_RecordedMeasurementContext")]
partial class RecordedMeasurementContext
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.Property<Guid>("ObservationId")
.HasColumnType("uuid")
.HasColumnName("observation_id");
b.Property<string>("Context")
.HasColumnType("character varying")
.HasColumnName("context");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<int>("Diastolic")
.HasColumnType("integer")
.HasColumnName("diastolic");
b.Property<DateTime>("MeasuredAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("measured_at");
b.Property<string>("Note")
.HasColumnType("character varying")
.HasColumnName("note");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<int>("Pulse")
.HasColumnType("integer")
.HasColumnName("pulse");
b.Property<int>("Systolic")
.HasColumnType("integer")
.HasColumnName("systolic");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("ObservationId");
b.ToTable("blood_pressure_observation", (string)null);
});
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.OwnsOne("ObservationService.Domain.MeasurementContext", "MeasurementContext", b1 =>
{
b1.Property<Guid>("BloodPressureObservationObservationId")
.HasColumnType("uuid");
b1.Property<string>("ActivityCondition")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("activity_condition");
b1.Property<string>("AdditionalCircumstances")
.HasColumnType("text")
.HasColumnName("additional_circumstances");
b1.Property<string>("BodyPosition")
.HasColumnType("text")
.HasColumnName("body_position");
b1.Property<string>("CuffDetails")
.HasColumnType("text")
.HasColumnName("cuff_details");
b1.Property<string>("DeviceDetails")
.HasColumnType("text")
.HasColumnName("device_details");
b1.Property<string>("MeasuredArm")
.HasColumnType("text")
.HasColumnName("measured_arm");
b1.Property<decimal?>("RestDurationMinutes")
.HasColumnType("numeric")
.HasColumnName("rest_duration_minutes");
b1.Property<string>("Setting")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("setting");
b1.HasKey("BloodPressureObservationObservationId");
b1.ToTable("blood_pressure_observation");
b1.WithOwner()
.HasForeignKey("BloodPressureObservationObservationId");
});
b.Navigation("MeasurementContext")
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,100 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
/// <inheritdoc />
public partial class RecordedMeasurementContext : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "activity_condition",
table: "blood_pressure_observation",
type: "text",
nullable: false,
defaultValue: "Unknown");
migrationBuilder.AddColumn<string>(
name: "additional_circumstances",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "body_position",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "cuff_details",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "device_details",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "measured_arm",
table: "blood_pressure_observation",
type: "text",
nullable: true);
migrationBuilder.AddColumn<decimal>(
name: "rest_duration_minutes",
table: "blood_pressure_observation",
type: "numeric",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "setting",
table: "blood_pressure_observation",
type: "text",
nullable: false,
defaultValue: "Unknown");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "activity_condition",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "additional_circumstances",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "body_position",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "cuff_details",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "device_details",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "measured_arm",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "rest_duration_minutes",
table: "blood_pressure_observation");
migrationBuilder.DropColumn(
name: "setting",
table: "blood_pressure_observation");
}
}
}
@@ -0,0 +1,131 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using ObservationService.Persistence;
#nullable disable
namespace ObservationService.Persistence.Migrations
{
[DbContext(typeof(ObservationDbContext))]
partial class ObservationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.Property<Guid>("ObservationId")
.HasColumnType("uuid")
.HasColumnName("observation_id");
b.Property<string>("Context")
.HasColumnType("character varying")
.HasColumnName("context");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<int>("Diastolic")
.HasColumnType("integer")
.HasColumnName("diastolic");
b.Property<DateTime>("MeasuredAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("measured_at");
b.Property<string>("Note")
.HasColumnType("character varying")
.HasColumnName("note");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<int>("Pulse")
.HasColumnType("integer")
.HasColumnName("pulse");
b.Property<int>("Systolic")
.HasColumnType("integer")
.HasColumnName("systolic");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("ObservationId");
b.ToTable("blood_pressure_observation", (string)null);
});
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
{
b.OwnsOne("ObservationService.Domain.MeasurementContext", "MeasurementContext", b1 =>
{
b1.Property<Guid>("BloodPressureObservationObservationId")
.HasColumnType("uuid");
b1.Property<string>("ActivityCondition")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("activity_condition");
b1.Property<string>("AdditionalCircumstances")
.HasColumnType("text")
.HasColumnName("additional_circumstances");
b1.Property<string>("BodyPosition")
.HasColumnType("text")
.HasColumnName("body_position");
b1.Property<string>("CuffDetails")
.HasColumnType("text")
.HasColumnName("cuff_details");
b1.Property<string>("DeviceDetails")
.HasColumnType("text")
.HasColumnName("device_details");
b1.Property<string>("MeasuredArm")
.HasColumnType("text")
.HasColumnName("measured_arm");
b1.Property<decimal?>("RestDurationMinutes")
.HasColumnType("numeric")
.HasColumnName("rest_duration_minutes");
b1.Property<string>("Setting")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("Unknown")
.HasColumnName("setting");
b1.HasKey("BloodPressureObservationObservationId");
b1.ToTable("blood_pressure_observation");
b1.WithOwner()
.HasForeignKey("BloodPressureObservationObservationId");
});
b.Navigation("MeasurementContext")
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore;
using ObservationService.Domain;
namespace ObservationService.Persistence;
public sealed class ObservationDbContext(DbContextOptions<ObservationDbContext> options) : DbContext(options)
{
public DbSet<BloodPressureObservation> Observations => Set<BloodPressureObservation>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var observation = modelBuilder.Entity<BloodPressureObservation>();
observation.ToTable("blood_pressure_observation");
observation.HasKey(o => o.ObservationId);
observation.Property(o => o.ObservationId).HasColumnName("observation_id").ValueGeneratedNever();
// An external patient identifier, not a cross-database foreign key.
observation.Property(o => o.PatientId).HasColumnName("patient_id");
observation.Property(o => o.MeasuredAt).HasColumnName("measured_at").HasColumnType("timestamp without time zone");
observation.Property(o => o.Systolic).HasColumnName("systolic");
observation.Property(o => o.Diastolic).HasColumnName("diastolic");
observation.Property(o => o.Pulse).HasColumnName("pulse");
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
observation.OwnsOne(o => o.MeasurementContext, context =>
{
context.Property(c => c.Setting).HasColumnName("setting").HasDefaultValue("Unknown").IsRequired();
context.Property(c => c.ActivityCondition).HasColumnName("activity_condition").HasDefaultValue("Unknown").IsRequired();
context.Property(c => c.RestDurationMinutes).HasColumnName("rest_duration_minutes");
context.Property(c => c.BodyPosition).HasColumnName("body_position");
context.Property(c => c.MeasuredArm).HasColumnName("measured_arm");
context.Property(c => c.DeviceDetails).HasColumnName("device_details");
context.Property(c => c.CuffDetails).HasColumnName("cuff_details");
context.Property(c => c.AdditionalCircumstances).HasColumnName("additional_circumstances");
});
observation.Navigation(o => o.MeasurementContext).IsRequired();
observation.Property(o => o.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
observation.Property(o => o.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
}
}
@@ -0,0 +1,79 @@
using ObservationService.Contracts;
using Microsoft.EntityFrameworkCore;
using ObservationService.Application;
using ObservationService.Domain;
namespace ObservationService.Persistence;
public sealed class SqlObservationRepository(ObservationDbContext db) : ObservationRepository
{
public async Task<bool> DeleteAsync(Guid observationId, CancellationToken cancellationToken) =>
await db.Observations.Where(o => o.ObservationId == observationId)
.ExecuteDeleteAsync(cancellationToken) > 0;
public async Task<BloodPressureObservation?> UpdateAsync(Guid observationId, PatchObservationRequest request,
DateTime updatedAt, CancellationToken cancellationToken)
{
var observation = await db.Observations.SingleOrDefaultAsync(o => o.ObservationId == observationId,
cancellationToken);
if (observation is null)
return null;
if (request.SystolicSpecified) observation.Systolic = request.Systolic!.Value;
if (request.DiastolicSpecified) observation.Diastolic = request.Diastolic!.Value;
if (request.PulseSpecified) observation.Pulse = request.Pulse!.Value;
if (request.ContextSpecified) observation.Context = request.Context;
if (request.NoteSpecified) observation.Note = request.Note;
if (request.MeasurementContextSpecified)
{
if (request.MeasurementContext is null) observation.MeasurementContext = new();
else
{
var patch = request.MeasurementContext;
var current = observation.MeasurementContext;
observation.MeasurementContext = current with
{
Setting = patch.SettingSpecified ? patch.Setting ?? "Unknown" : current.Setting,
ActivityCondition = patch.ActivityConditionSpecified ? patch.ActivityCondition ?? "Unknown" : current.ActivityCondition,
RestDurationMinutes = patch.RestDurationMinutesSpecified ? patch.RestDurationMinutes : current.RestDurationMinutes,
BodyPosition = patch.BodyPositionSpecified ? patch.BodyPosition : current.BodyPosition,
MeasuredArm = patch.MeasuredArmSpecified ? patch.MeasuredArm : current.MeasuredArm,
DeviceDetails = patch.DeviceDetailsSpecified ? patch.DeviceDetails : current.DeviceDetails,
CuffDetails = patch.CuffDetailsSpecified ? patch.CuffDetails : current.CuffDetails,
AdditionalCircumstances = patch.AdditionalCircumstancesSpecified ? patch.AdditionalCircumstances : current.AdditionalCircumstances
};
}
}
observation.UpdatedAt = updatedAt;
await db.SaveChangesAsync(cancellationToken);
return observation;
}
public async Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken)
{
db.Observations.Add(observation);
await db.SaveChangesAsync(cancellationToken);
return observation;
}
public Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
db.Observations.AsNoTracking().SingleOrDefaultAsync(o => o.ObservationId == observationId, cancellationToken);
public Task<BloodPressureObservation?> FindLatestByPatientIdAsync(Guid patientId, CancellationToken cancellationToken) =>
db.Observations.AsNoTracking().Where(o => o.PatientId == patientId)
.OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.CreatedAt)
.ThenByDescending(o => o.ObservationId)
.FirstOrDefaultAsync(cancellationToken);
public Task<List<BloodPressureObservation>> FindByPatientIdAndPeriodAsync(Guid patientId, DateTime from, DateTime to,
ContextSelection selection, CancellationToken cancellationToken)
{
var query = db.Observations.AsNoTracking()
.Where(o => o.PatientId == patientId && o.MeasuredAt >= from && o.MeasuredAt <= to);
if (selection.Setting is not null)
query = query.Where(o => o.MeasurementContext.Setting == selection.Setting);
if (selection.ActivityCondition is not null)
query = query.Where(o => o.MeasurementContext.ActivityCondition == selection.ActivityCondition);
return query.OrderBy(o => o.MeasuredAt).ThenBy(o => o.ObservationId).ToListAsync(cancellationToken);
}
}
@@ -0,0 +1,74 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;
using ObservationService.Application;
using ObservationService.Persistence;
namespace ObservationService;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-observation");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddDbContext<ObservationDbContext>((services, options) =>
options.UseNpgsql(services.GetRequiredService<IConfiguration>().GetConnectionString("ObservationDatabase")));
builder.Services.AddScoped<ObservationRepository, SqlObservationRepository>();
builder.Services.AddScoped<ObservationApplicationService>();
builder.Services.AddHttpClient("ApiGateway", (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 (string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("ObservationDatabase")))
throw new InvalidOperationException("ConnectionStrings:ObservationDatabase must be configured.");
if (args.Contains("--migrate"))
{
await using var scope = app.Services.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<ObservationDbContext>().Database.MigrateAsync();
return;
}
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();
await app.RunAsync();
}
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,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
}
@@ -0,0 +1,45 @@
using PatientProfileService.Contracts;
using PatientProfileService.Domain;
namespace PatientProfileService.Application;
public sealed class PatientApplicationService(PatientRepository repository)
{
public async Task<Patient> CreatePatientAsync(CreatePatientRequest request, string accountId, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
ArgumentException.ThrowIfNullOrWhiteSpace(accountId);
if (await repository.FindByAccountIdAsync(accountId, cancellationToken) is not null)
throw new ProfileAlreadyExistsException();
if (request.DateOfBirth is null)
throw new ArgumentException("A date of birth is required.", nameof(request));
// The documented TIMESTAMP columns store UTC without a time-zone component.
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
return await repository.SaveAsync(new Patient
{
PatientId = Guid.NewGuid(),
AccountId = accountId,
Name = request.Name,
DateOfBirth = request.DateOfBirth.Value,
ContactInfo = request.ContactInfo,
CreatedAt = now,
UpdatedAt = now
}, cancellationToken);
}
public Task<Patient?> GetByAccountAsync(string accountId, CancellationToken cancellationToken) =>
repository.FindByAccountIdAsync(accountId, cancellationToken);
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindByIdAsync(patientId, cancellationToken);
public async Task<Patient?> UpdatePatientAsync(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
if (!await repository.UpdateProfileAsync(patientId, request.Name, request.ContactInfo, cancellationToken))
return null;
return await repository.FindByIdAsync(patientId, cancellationToken);
}
}
@@ -0,0 +1,11 @@
using PatientProfileService.Domain;
namespace PatientProfileService.Application;
public interface PatientRepository
{
Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken);
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
}
@@ -0,0 +1,5 @@
namespace PatientProfileService.Application;
public sealed class ProfileAlreadyExistsException : Exception
{
}
@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
namespace PatientProfileService.Contracts;
public sealed record CreatePatientRequest
{
[Required]
public string? Name { get; init; }
[Required]
public DateOnly? DateOfBirth { get; init; }
public string? ContactInfo { get; init; }
}
@@ -0,0 +1,3 @@
namespace PatientProfileService.Contracts;
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace PatientProfileService.Contracts;
public sealed record UpdatePatientRequest
{
[Required]
public string? Name { get; init; }
public string? ContactInfo { get; init; }
}
@@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Mvc;
using PatientProfileService.Application;
using PatientProfileService.Contracts;
using PatientProfileService.Domain;
namespace PatientProfileService.Controllers;
[ApiController]
[Route("api/patients")]
public sealed class PatientController(PatientApplicationService service) : ControllerBase
{
[HttpPost]
public async Task<ActionResult<PatientDto>> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken)
{
var accountId = Request.Headers["X-Account-Id"].ToString();
if (string.IsNullOrWhiteSpace(accountId)) return BadRequest();
try
{
var patient = await service.CreatePatientAsync(request, accountId, cancellationToken);
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
}
catch (ProfileAlreadyExistsException)
{
return Conflict(new { title = "A profile already exists for this account." });
}
}
[HttpGet("by-account/{accountId}")]
public async Task<ActionResult<PatientDto>> GetByAccount(string accountId, CancellationToken cancellationToken)
{
var patient = await service.GetByAccountAsync(accountId, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
[HttpGet("{patientId:guid}")]
public async Task<ActionResult<PatientDto>> GetPatient(Guid patientId, CancellationToken cancellationToken)
{
var patient = await service.GetPatientAsync(patientId, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
[HttpPut("{patientId:guid}")]
public async Task<ActionResult<PatientDto>> UpdatePatient(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
{
var patient = await service.UpdatePatientAsync(patientId, request, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
private static PatientDto ToDto(Patient patient) =>
new(patient.PatientId, patient.Name, patient.DateOfBirth, patient.ContactInfo);
}
@@ -0,0 +1,12 @@
namespace PatientProfileService.Domain;
public sealed class Patient
{
public string? AccountId { get; set; }
public Guid PatientId { get; set; }
public string Name { get; set; } = "";
public DateOnly DateOfBirth { get; set; }
public string? ContactInfo { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.12" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
</ItemGroup>
</Project>
@@ -0,0 +1,62 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PatientProfileService.Persistence;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
[DbContext(typeof(PatientDbContext))]
[Migration("20260930200031_InitialPatientSchema")]
partial class InitialPatientSchema
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("PatientProfileService.Domain.Patient", b =>
{
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("ContactInfo")
.HasColumnType("character varying")
.HasColumnName("contact_info");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<DateOnly>("DateOfBirth")
.HasColumnType("date")
.HasColumnName("date_of_birth");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("character varying")
.HasColumnName("name");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("PatientId");
b.ToTable("patient", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
/// <inheritdoc />
public partial class InitialPatientSchema : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "patient",
columns: table => new
{
patient_id = table.Column<Guid>(type: "uuid", nullable: false),
name = table.Column<string>(type: "character varying", nullable: false),
date_of_birth = table.Column<DateOnly>(type: "date", nullable: false),
contact_info = table.Column<string>(type: "character varying", nullable: true),
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_patient", x => x.patient_id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "patient");
}
}
}
@@ -0,0 +1,69 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PatientProfileService.Persistence;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
[DbContext(typeof(PatientDbContext))]
[Migration("20261005082209_AccountProfileAssociation")]
partial class AccountProfileAssociation
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("PatientProfileService.Domain.Patient", b =>
{
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("AccountId")
.HasColumnType("text")
.HasColumnName("account_id");
b.Property<string>("ContactInfo")
.HasColumnType("character varying")
.HasColumnName("contact_info");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<DateOnly>("DateOfBirth")
.HasColumnType("date")
.HasColumnName("date_of_birth");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("character varying")
.HasColumnName("name");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("PatientId");
b.HasIndex("AccountId")
.IsUnique();
b.ToTable("patient", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
/// <inheritdoc />
public partial class AccountProfileAssociation : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "account_id",
table: "patient",
type: "text",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_patient_account_id",
table: "patient",
column: "account_id",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_patient_account_id",
table: "patient");
migrationBuilder.DropColumn(
name: "account_id",
table: "patient");
}
}
}
@@ -0,0 +1,66 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PatientProfileService.Persistence;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
[DbContext(typeof(PatientDbContext))]
partial class PatientDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("PatientProfileService.Domain.Patient", b =>
{
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("AccountId")
.HasColumnType("text")
.HasColumnName("account_id");
b.Property<string>("ContactInfo")
.HasColumnType("character varying")
.HasColumnName("contact_info");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<DateOnly>("DateOfBirth")
.HasColumnType("date")
.HasColumnName("date_of_birth");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("character varying")
.HasColumnName("name");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("PatientId");
b.HasIndex("AccountId")
.IsUnique();
b.ToTable("patient", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,24 @@
using Microsoft.EntityFrameworkCore;
using PatientProfileService.Domain;
namespace PatientProfileService.Persistence;
public sealed class PatientDbContext(DbContextOptions<PatientDbContext> options) : DbContext(options)
{
public DbSet<Patient> Patients => Set<Patient>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var patient = modelBuilder.Entity<Patient>();
patient.ToTable("patient");
patient.HasKey(p => p.PatientId);
patient.Property(p => p.AccountId).HasColumnName("account_id");
patient.HasIndex(p => p.AccountId).IsUnique();
patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired();
patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date");
patient.Property(p => p.ContactInfo).HasColumnName("contact_info").HasColumnType("character varying");
patient.Property(p => p.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
patient.Property(p => p.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
}
}
@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore;
using Npgsql;
using PatientProfileService.Application;
using PatientProfileService.Domain;
namespace PatientProfileService.Persistence;
public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepository
{
public async Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken)
{
db.Patients.Add(patient);
try { await db.SaveChangesAsync(cancellationToken); }
catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: "23505", ConstraintName: "IX_patient_account_id" })
{
throw new ProfileAlreadyExistsException();
}
return patient;
}
public Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken) =>
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.AccountId == accountId, cancellationToken);
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
public async Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken)
{
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
var affected = await db.Patients.Where(p => p.PatientId == patientId)
.ExecuteUpdateAsync(update => update
.SetProperty(p => p.Name, name)
.SetProperty(p => p.ContactInfo, contactInfo)
.SetProperty(p => p.UpdatedAt, now), cancellationToken);
return affected != 0;
}
}
@@ -0,0 +1,48 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;
using PatientProfileService.Application;
using PatientProfileService.Persistence;
namespace PatientProfileService;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(options => options.ServiceName = "healthapp-patient-profile");
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddDbContext<PatientDbContext>((services, options) =>
options.UseNpgsql(services.GetRequiredService<IConfiguration>().GetConnectionString("PatientDatabase")));
builder.Services.AddScoped<PatientRepository, SqlPatientRepository>();
builder.Services.AddScoped<PatientApplicationService>();
var app = builder.Build();
if (string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("PatientDatabase")))
throw new InvalidOperationException("ConnectionStrings:PatientDatabase must be configured.");
if (args.Contains("--migrate"))
{
await using var scope = app.Services.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<PatientDbContext>().Database.MigrateAsync();
return;
}
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();
await app.RunAsync();
}
}
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
}
+346
View File
@@ -0,0 +1,346 @@
# 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, 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.
US-13 now protects the patient-data APIs. Read [AUTHENTICATION.md](AUTHENTICATION.md)
for login, persistent profile ownership, deployment credentials and token settings.
Configure the required keys/accounts before startup. The revised US-01 creation
lifecycle is included. US-14 now permits read-only access to assigned patients.
## Build and run
Load external service configuration using the updated `deploy/*.env.example` templates.
Use HTTPS certificates for all production endpoints. For local HTTP development
only, set `ASPNETCORE_ENVIRONMENT=Development` on each process; all credentials and
the gateway key directory are still required.
Install a .NET 10 SDK and provision an empty PostgreSQL database owned by the Patient/Profile service's database user. From the repository root:
```bash
dotnet restore HealthApp.slnx
dotnet build HealthApp.slnx -c Release --no-restore
# In the Patient/Profile service terminal; substitute your own database configuration.
export ConnectionStrings__PatientDatabase='Host=127.0.0.1;Database=patient_profile;Username=patient_profile;Password=YOUR_LOCAL_PASSWORD'
dotnet run --project src/PatientProfileService -c Release --no-build -- --migrate
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/ 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'
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
# 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.
## API
Send requests to the gateway:
```bash
curl -i http://127.0.0.1:5080/api/patients \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_LOGIN_TOKEN' \
-d '{"name":"Steffen Example","dateOfBirth":"1980-01-01","contactInfo":"steffen@example.test"}'
```
`POST /api/authentication/login` accepts `accountId` and `password` and returns a
protected access token. Include `Authorization: Bearer YOUR_LOGIN_TOKEN` on each
patient-data request below. Initial profile creation is permitted once per patient
account; repeated/concurrent attempts report `409`. `GET /api/patients/me` retrieves
the account’s profile when its generated identifier is not yet known.
`POST /api/patients` returns `201 Created`, a relative `Location: /api/patients/{patientId}` header, and a JSON profile containing `patientId`, `name`, `dateOfBirth`, and `contactInfo`. Identifiers are generated UUIDs and the database primary key enforces uniqueness. Names must be nonblank; dates of birth must be supplied as valid `YYYY-MM-DD` dates. Invalid requests return `400` validation problem details and do not create profiles. Contact information is optional because US-01 does not require it.
`GET /api/patients/{patientId}` retrieves the persisted profile, or returns `404` when absent. Retrieval is included because US-01 explicitly requires it. The gateway returns `502` for connection failures and `504` for upstream timeouts.
`PUT /api/patients/{patientId}` updates the name and contact information and returns `200` with the updated profile. It preserves the patient identifier, date of birth and creation timestamp, and updates the modification timestamp. Names must be nonblank, consistent with profile creation; omitted or null contact information clears that optional value. A missing patient returns `404` without creating a profile. Invalid requests return `400` without changing stored information.
`POST /api/patients/{patientId}/observations` records a blood-pressure observation. Supply `measuredAt`, positive integer `systolic`, `diastolic` and `pulse`, plus optional `measurementContext`, legacy `context` and `note`. It returns `201`, the saved observation including its generated `observationId` and `patientId`, and `Location: /api/observations/{observationId}`. `GET` at that location retrieves the persisted observation, or returns `404` if absent. Retrieval is included to satisfy US-04's requirement that a recorded observation can be retrieved later.
US-04 now supports structured context independently of legacy free text:
```json
{
"measuredAt": "2026-09-12T08:00:00Z",
"systolic": 128,
"diastolic": 82,
"pulse": 68,
"measurementContext": {
"setting": "Home",
"activityCondition": "AtRest",
"restDurationMinutes": 5.5,
"bodyPosition": "Seated",
"measuredArm": "Left",
"deviceDetails": "Example upper-arm device",
"cuffDetails": "Example cuff",
"additionalCircumstances": "Recent stress"
},
"context": "Before breakfast",
"note": "Actual reading"
}
```
Supported `setting` values are `Home`, `Clinic`, `Other`, and `Unknown`;
`activityCondition` values are `AtRest`, `DuringActivity`, `AfterActivity`, and
`Unknown`. Category names are case-sensitive. Omitted/null categories, or an
omitted/null object, become `Unknown`; other omitted details stay null. Unsupported
categories and malformed fields return `400` validation details without saving.
Rest duration is optional, in minutes, and may be zero or any nonnegative decimal.
There is no minimum rest duration or posture requirement for accepting a reading.
The remaining optional details are narrative text, not technique certification.
Legacy context and notes are retained verbatim, including conflicts with categories;
no category is inferred from free text. Interpretation of conflicts belongs to
US-11. The structured object is included on observation reads and numeric-update
responses, including latest/history through their existing observation DTO.
Apply the `RecordedMeasurementContext` Observation migration before starting the
updated service. EF Core maps the owned value to columns in the same observation
table; no new table, service or dependency is introduced. Existing rows receive
unknown categories and null details without changing their measurements, timestamps
or text. Context filtering is implemented under US-07; partial context updates are implemented under US-08.
US-05 context retrieval is covered independently of creation: dedicated tests seed
saved observations directly and request them through the authenticated gateway.
They verify complete context with its measurements/timestamp after restart, partial
and unknown context, preservation of historical free text, missing-observation
behaviour, rejected unauthorised reads, and identical context for an assigned
professional and the owner. This uses the existing retrieval endpoint and DTO added
with US-04; no further production code or migration is needed for US-05.
The Observation Service checks patient existence by calling the gateway's patient retrieval API over HTTP before saving. It has no reference to Patient/Profile implementation code and no access to that service's database. Missing patients return `404`; validation failures return `400`. Patient lookup failures return `502` or `504` and do not save an observation. Measurement timestamps without an offset represent UTC clock values and are stored as supplied, independently of the host time zone; timestamps with an offset are normalized to UTC. PostgreSQL uses the diagram's `timestamp` columns without a time-zone component.
`GET /api/patients/{patientId}/observations/latest` returns `200` with that patient's observation having the greatest measurement timestamp, regardless of recording order. It returns `404` when no observation is available. Equal measurement timestamps are resolved by greatest original recording timestamp (`created_at`), then greatest observation UUID under PostgreSQL UUID ordering if recording times also tie. Edits preserve original recording time and do not affect tie selection. Context completeness does not affect selection; the returned observation includes its own saved context. Selection happens in the Observation Service's own database through the documented controller/application-service/repository layers.
US-06 acceptance tests cover out-of-order measurements, patient-specific selection, context independent of suitability/completeness, recording-time ties, later edits, reproducible complete ties across restart, and no available observation even when another patient has recorded measurements. No new dependencies or schema changes are required.
`GET /api/patients/{patientId}/observations?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with a JSON array of that patient's observations within the inclusive measurement-time bounds, ordered chronologically. A valid period with no matches returns `[]`. Both timestamps are required; missing, malformed, or reversed bounds return `400` validation problem details. Equal bounds are valid. Offset timestamps are normalized to UTC consistently with recording; encode `+` as `%2B` in query parameters. Equal measurement timestamps are ordered by observation identifier. The query runs in the Observation Service's own database; no patient-profile lookup is needed.
US-07 now accepts optional `setting` and `activityCondition` query selections using
the same case-sensitive categories as recording. For example, append
`&setting=Home&activityCondition=AtRest` to retrieve only home-resting observations.
Both supplied dimensions must match. `Unknown` explicitly selects a missing or
unknown category; omitted/empty query values apply no restriction on that dimension.
Legacy text is preserved but never establishes a known category match.
The JSON response remains an observation array, including `measurementContext` on
each observation. Applied selections are reported on successful responses in
`X-Measurement-Setting` and `X-Activity-Condition` headers. Each contains the selected
category or `All` for an unrestricted dimension; `All` is response metadata, not an
accepted query category. The gateway forwards these two headers. Empty selections
return `[]` with the same selection metadata. Unsupported selections return `400`
validation problem details without changes to observations. Filtering is performed
in the Observation database within the original patient/inclusive-period query,
retaining chronological order and the existing equal-time identifier ordering.
US-07 tests cover original history criteria plus independent/combined/unknown
context selections, response metadata including empty results, complete/partial/
absent context, legacy-text preservation, patient-specific access, inclusive/equal
and offset bounds, persistence after restart, and invalid selections without writes.
Existing Insights requests continue to consume the unchanged unfiltered array. No new dependencies or schema changes are required.
`PUT /api/observations/{observationId}` corrects the measured values using a JSON body containing required positive integer `systolic`, `diastolic`, and `pulse` fields. It returns `200` with the updated observation, preserving its identifier, patient, measurement time, context, note, and creation timestamp while updating the modification timestamp. Missing observations return `404` without insertion; invalid requests return `400` without changes. Corrections are visible through specific retrieval, latest retrieval, and history. The Observation Service owns the update; no patient-profile lookup or database schema change is required.
`PATCH /api/observations/{observationId}` accepts a partial JSON object. For example:
```json
{
"measurementContext": {
"setting": "Clinic",
"activityCondition": null,
"deviceDetails": "Corrected device"
}
}
```
Only supplied fields change. Within `measurementContext`, setting/activity nulls
clear the category to `Unknown`; null optional details clear them without changing
other details. An explicit `measurementContext: null` clears the whole structured
object to unknown categories and null details, while retaining legacy text and
notes. Omission of the object preserves it. Optional `context` and `note` can also
be changed or cleared with null. Optional `systolic`, `diastolic` and `pulse` support
individual positive-integer corrections; they cannot be cleared. Empty patches or
objects containing no supported changes return `400`. Creation time, measurement
time, patient association and observation identifier cannot be changed by patches.
Successful patches return `200` with the updated observation and modification time.
Validation occurs before any changes are saved; unsupported fields/categories, negative
rest duration, non-positive/null numerical values and malformed input reject the
whole request with `400` validation details. Missing observations return `404`
without insertion. Ownership restrictions apply to the actual observation patient;
professionals cannot patch even assigned patients. The existing `PUT` endpoint
retains its complete numerical-correction contract and rejects unsupported fields
rather than silently ignoring context supplied on that route. Use `PATCH` for context
updates. Both routes use the same
Observation-owned update operation and save changes atomically. Subsequent reads,
latest observations and filtered history use current recorded context. US-11 trend assessments also use current recorded context on each request.
US-08 tests cover the original full numerical corrections and rejection scenarios plus context-only/single-value patches, historical context additions, individual field corrections/clears, whole-context clearing, preservation of omitted data and creation time, persistence after restart, fresh filter membership, atomic rejection, missing observations and access restrictions. No new dependencies are introduced.
`DELETE /api/observations/{observationId}` removes the observation and returns `204 No Content`. A missing or previously deleted observation returns `404`. The Observation Service deletes the row from its own database in a single statement; deleted observations disappear from specific retrieval, history, and latest selection. Other observations and the patient profile are preserved.
US-09 tests cover the original deletion scenarios plus structured-context removal, filtered history after restart, current numerical summaries excluding deleted values, preservation of other observations and their context, empty filtered results, repeated deletion, and rejection of unauthenticated/other-patient/professional deletion. Context is stored in the observation row, so its existing atomic deletion needs no new production operation. US-11 tests verify fresh trends after deletion. 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. Arithmetic means use decimal calculations and round only the final result to two decimal places, half-up (away from zero for the positive recorded values); extrema retain their recorded integer values. 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 supports the same optional `setting` and `activityCondition` selections as
history, including explicit `Unknown` and combined matching. For example append
`&setting=Home&activityCondition=AtRest`. Omitted/empty selections include all
otherwise eligible observations. Unsupported categories return `400` validation
details. Selection that leaves no observations returns the existing insufficient-
data `404` response. Selection is forwarded through the gateway to the Observation
Service; no service implementation is referenced directly.
Successful insights also include `appliedSelection` (nullable `setting` and
`activityCondition` mean unrestricted), `contributingCount`, and
`contextExplanation`. The explanation reports recorded setting/activity counts,
mixed/unknown categories, missing optional context details and differences in
recorded optional details. It describes numerical aggregation without certifying
measurement technique, clinical comparability or completion of a diagnostic
monitoring protocol. Legacy narrative text is retained by the observation contract
but never used to invent categories. Preparation differences are reported as
recorded differences, not a clinical classification.
The rounding contract applies to all three means: seven readings of 120 and one
of 121 yield 120.13; 120, 120 and 121 yield 120.33. No intermediate rounding occurs.
Single-observation means equal the recorded values, and blood-pressure minimum and
maximum are equal. Numeric JSON need not retain trailing zeros. New requests always
use current observations/context after corrections, clearing and deletion.
US-10 tests use all four HTTP hosts and the existing separate patient/observation
test databases. They cover original summaries, independent/combined/unknown
selections, applied selections and counts, context explanations, one-observation
results, halfway/repeating rounding for all three metrics, patient/inclusive/equal/
offset bounds, context corrections/clearing/deletions, restart, invalid requests,
professional assignments and unavailable observation retrieval. Insights introduces no external dependencies. US-11 adds the separate trend endpoint described in [TRENDS.md](TRENDS.md).
`GET /api/patients/{patientId}/trends?from=...&to=...` implements US-11 with independent
systolic, diastolic and pulse assessments, context selections/counts, recorded comparability,
full-period numerical direction, reversals and variation, sourced reference comparisons and
limited clinical interpretation. Empty/single/tied series report unavailable temporal direction;
numerical information remains where supported. See [TRENDS.md](TRENDS.md) for the response,
reproducible mathematical methods, reference sources and interpretation limits. Tests cover
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
writes are rejected. US-04 through US-11 include updated context, ordering, rounding and trend requirements.
## Automated acceptance tests
### US-15 public measurement guidance
`GET /api/measurement-guidance` returns ordered instructions for resting home
self-measurement, with source URLs, source update dates and review date. It works
before a patient or observation exists and requires no authentication or upstream
service access. The gateway serves this static general content without persistence.
Optional `setting` accepts `Home`, `Clinic`, `Other`, or `Unknown`; omission means
unknown. Home or unknown requests return explicitly labelled home instructions;
clinic/other requests return `available: false` and no instructions because no
verified guidance for those settings is bundled. Optional `activityCondition`
accepts `AtRest`, `DuringActivity`, `AfterActivity`, or `Unknown`. The response
preserves requested conditions while identifying the resting applicability of the
instructions. Unsupported categories return `400` problem details.
The bundled content was reviewed on 2026-10-04 against the two Sundhed.dk pages
specified in US-15. It distinguishes the planned Danish three-day monitoring
protocol from an individual observation. Review sources again when updating the
content; requests do not fetch live guidance. Viewing/declining instructions never
records context, certifies compliance or gates observation submission. Pulse
information describes the device-reported rate rather than rhythm assessment.
The `MeasurementGuidanceTests` HTTP tests need no PostgreSQL server and cover
public access, ordered sourced content, unknown setting, activity limitations,
unavailable guidance, invalid selections, and absence of patient-service calls.
Run them with `dotnet test tests/PatientProfile.AcceptanceTests -c Release --filter
FullyQualifiedName~MeasurementGuidanceTests`. Existing observation recording tests
cover submission without viewing guidance. No dependencies were added.
Tests require a real PostgreSQL instance. Provide an administrator connection with permission to create/drop databases; the fixture creates an isolated database named `us01_<random>`, applies the committed migration, and deletes that database at teardown. Never point this connection at a production server.
```bash
TEST_POSTGRES_CONNECTION='Host=127.0.0.1;Database=postgres;Username=postgres;Password=YOUR_LOCAL_TEST_PASSWORD' \
dotnet test HealthApp.slnx -c Release
```
The xUnit tests send HTTP requests to the gateway; the gateway reaches a real Kestrel Patient/Profile service over HTTP. They cover every US-01 acceptance scenario, retrieval after host restart, distinct identifiers, optional contact information, invalid JSON/dates, and rejection without database writes. Test assertions use an independent HTTP response contract. Production projects have no references to each other's implementation.
US-02 retrieval scenarios are covered by the creation tests. US-03 tests cover persisted updates after restart, preservation of identity and date of birth, missing-patient rejection without insertion, and invalid-name rejection without changing the profile.
US-04 tests use real HTTP between the hosts and separate temporary patient and observation databases. They cover every recording acceptance scenario, retrieval after restart, optional fields, distinct identifiers, malformed/missing fields, missing observations, and patient-lookup failure without database writes. Both services' committed migrations are applied twice to verify idempotence. Context tests also verify complete/partial/absent context, departures from guidance, validation without writes, authorised professional reads, restart persistence, numeric-update preservation, and upgrading historical observations without deriving categories from free text. The Observation Service uses the same EF Core PostgreSQL dependencies as Patient/Profile for its independent persistence; no new library types are introduced.
Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency.
## Provisioning installer (US-16)
Build a portable release using `bash deploy/build-release.sh --output NEW_DIRECTORY`.
A normal supported Linux installation is `sudo bash install.sh --services all --host
DNS_OR_IP`; it provisions missing runtime/PostgreSQL dependencies, separate databases
and roles, generated service/account credentials, HTTPS/trust, independent configuration,
migrations, service registration/startup and installation verification. No prepared env
files, service passwords or prototype certificates are required.
Shared C# provisioning also generates Windows/macOS configuration. Native adapters use
Windows Services or launchd without changing application binaries/service boundaries.
See [INSTALLATION.md](../deploy/INSTALLATION.md) for supported hosts, native commands,
automatic SSH topology distribution, generated credentials and test evidence/limitations.
The existing `deploy/*.env.example` files remain useful for advanced/manual development;
they are no longer prerequisites for the normal installer.
## Linux deployment
Publish each service separately:
```bash
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
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.
Apply the database migration using the published Patient/Profile executable with its database configuration:
```bash
dotnet /opt/healthapp/patient-profile/PatientProfileService.dll --migrate
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.
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.
+85
View File
@@ -0,0 +1,85 @@
# US-11 trend API and methods
`GET /api/patients/{patientId}/trends?from=...&to=...&setting=Home&activityCondition=AtRest`
uses the same inclusive UTC measurement-instant semantics and optional context selections as history and
numerical insight. Offset-free timestamps mean UTC. Both selected dimensions must match; `Unknown`
is an explicit category. Patient ownership or professional assignment is required. Each selection is a
separate labelled result for the same requested period. No cross-setting difference is interpreted as
improvement. Insights retrieves current observations through the gateway on every request, without persistence.
A valid request returns 200 even for an empty selection. Count zero, null descriptive values and explicit
`Unavailable` direction distinguish empty data from upstream failures (502/504). One observation or
all observations at a single instant retain descriptive values, but temporal direction is unavailable.
Invalid/missing period or unsupported selections return 400. No new configuration or dependencies are required.
## Numerical method
Each metric has its own unit, mean, minimum, maximum and range over every eligible observation. Decimal
means are rounded only for output, to two decimals with midpoint rounding away from zero. No numerical
range threshold is used to declare clinical stability or instability.
Temporal calculations group equal measurement instants using the arithmetic mean for each metric,
then order those groups by measurement instant. Identifier and storage order play no part. Direction
uses every adjacent nonzero change: all positive means Increasing, all negative Decreasing, both signs
Mixed, all zero NoClearDirection. Reversal count counts sign changes after excluding zero steps.
TotalSuccessiveChange sums absolute changes between consecutive timestamp means. This retains intermediate
excursions, while raw min/max retain differences within timestamp ties. No temporal change is assigned
between measurements at the same instant.
OverallDirection additionally reports the sign of an ordinary least-squares line over all timestamp
means. Time is scaled from zero to one over the observed span; each distinct timestamp has equal weight.
SlopePerDay converts that fitted slope to metric units per day and rounds to six decimals. Classification
uses the unrounded slope. An extremely small nonzero slope may round to zero; its sign is a mathematical
result, not evidence of clinical significance. The fit describes a linear tendency, not a prediction,
causal effect or a monotonic trajectory. Mixed direction and reversal count remain visible even when
an overall slope exists. Irregular sampling and repeated observations can affect the description;
there is no significance test, smoothing, diagnostic protocol or clinical variability classification.
## Context and interpretation
Comparability lists known similarities, differences and missing information for setting, activity,
rest duration, body position, measured arm, device and cuff. Differing recorded additional circumstances
also limit comparability. Matching complete recorded fields support comparability of recorded details
only, without certifying clinical technique or equipment. Missing optional additional circumstances do
not block a supported reference comparison. Known inadequate rest is reported separately.
Limited deterministic conflict detection recognises case-insensitive `during exercise`, `during activity`,
`after exercise`, `after activity`, `under motion`, `under træning`, `efter motion`, `efter træning` against
AtRest; `at clinic`, `in clinic`, `at the clinic`, `på klinik`, `hos lægen` against Home; and `at home`,
`hjemme` against Clinic. It examines preserved context, notes and recorded preparation text, without
recategorising observations. This is conservative phrase detection, not general language understanding;
negated phrases can still withhold interpretation. Arbitrary narrative is not proof of correct technique.
Detected conflicts withhold resting-reference interpretation while preserving numerical information.
Sources reviewed 2026-10-05:
- [Lægehåndbogen: Højt blodtryk](https://www.sundhed.dk/sundhedsfaglig/laegehaandbogen/hjerte-kar/symptomer-og-tegn/hoejt-blodtryk/)
(updated 2024-09-25): separate high-pressure boundaries of home 135/85 and clinic 140/90 mmHg,
inclusive. The reference comparison requires a single known setting and recorded AtRest; known rest
below five minutes or a non-seated recorded position prevents it. Missing optional preparation
details permit only a provisional comparison, explicitly identifying unknown technique. Arbitrary
period means do not establish the source's diagnostic protocol. No lower BP boundary is inferred.
- [Patienthåndbogen: Bradykardi](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/)
(updated 2025-09-02) and [Hurtig puls](https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/)
(updated 2025-05-12): resting pulse below 50 or above 100 beats/min provides limited rate-reference
comparisons. Low pulse can be physiological in trained people. Rate alone does not diagnose rhythm
abnormalities; age, fitness, medicines and symptoms remain unknown. These boundaries are not a
universal healthy range or a patient-specific target.
Every metric returns its reference scope, exact comparison operators, source URLs, update/review dates,
counts outside the boundaries and limitations. Comparisons remain available despite missing preparation
information when the known context supports that limited comparison. Mixed or unknown activity,
conflicting narrative, mixed BP settings, or unsupported BP setting make the affected comparison unavailable.
Interpretation of development requires temporal separation, applicable references and supported recorded
comparability. The following are deliberately cautious inferences from the cited references, not new
clinical decision rules: a consistent fall from high BP that remains high may be PotentiallyFavourable,
while explicitly still high; resting pulse moving from outside towards the reference interval may be
PotentiallyFavourable unless any contributing observation crosses the opposite boundary, including values within timestamp ties. Excursions outside a boundary with reversals
are Mixed. Other outside-reference levels may be PotentiallyConcerning, including falling low pulse
or unchanging high BP. Remaining cases are CannotInterpret. No BP fall below the high threshold is
automatically called favourable, because an applicable lower limit or personalised goal is unavailable.
Each hint distinguishes numerical variation from clinical meaning, explains incomplete/differing context,
and disclaims diagnosis and medication advice. There is no combined good/bad classification across metrics.
Reference comparisons and hints are for review, not a replacement for individual clinical assessment.