Record Architecture B approval and verified pinned baseline
This commit is contained in:
1 parent
20ab461c01
commit
cee98e7035
158 files changed
+33575
No files matched your search
+30
@@ -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.");
|
||||
}
|
||||
}
|
||||
+24
@@ -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);
|
||||
+34
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user