Deliver portable native Architecture B deployment and final verification
This commit is contained in:
1 parent
f451b55de1
commit
36740d2492
92 files changed
+10939
-926
No files matched your search
@@ -1,12 +1,13 @@
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public interface ReferenceCatalog
|
||||
{
|
||||
ClinicalReference Pulse();
|
||||
ClinicalReference Pressure(string metric,string setting);
|
||||
string Version {get;}
|
||||
ClinicalReference Pulse();
|
||||
ClinicalReference Pressure(string metric, string setting);
|
||||
string Version { get; }
|
||||
}
|
||||
public interface AnalyticsQueries
|
||||
{
|
||||
Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
|
||||
Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
|
||||
Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct);
|
||||
Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct);
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp")]
|
||||
[assembly: InternalsVisibleTo("HealthApp")]
|
||||
namespace HealthApp.Contracts;
|
||||
// Only the API/access assembly issues this request-local capability after policy checks.
|
||||
public sealed class AuthorizedPatientContext
|
||||
{
|
||||
internal AuthorizedPatientContext(Guid patientId, bool canWrite){PatientId=patientId;CanWrite=canWrite;}
|
||||
public Guid PatientId {get;}
|
||||
public bool CanWrite {get;}
|
||||
public void RequireWrite(){if(!CanWrite)throw new UnauthorizedAccessException("Read-only scope.");}
|
||||
internal AuthorizedPatientContext(Guid patientId, bool canWrite) { PatientId = patientId; CanWrite = canWrite; }
|
||||
public Guid PatientId { get; }
|
||||
public bool CanWrite { get; }
|
||||
public void RequireWrite() { if (!CanWrite) throw new UnauthorizedAccessException("Read-only scope."); }
|
||||
}
|
||||
public interface ProfileQueries
|
||||
{
|
||||
Task<Guid?> ResolveAccountAsync(string accountId,CancellationToken ct);
|
||||
Task<PatientDto?> GetAsync(AuthorizedPatientContext scope,CancellationToken ct);
|
||||
Task<Guid?> ResolveAccountAsync(string accountId, CancellationToken ct);
|
||||
Task<PatientDto?> GetAsync(AuthorizedPatientContext scope, CancellationToken ct);
|
||||
}
|
||||
public interface ProfileCommands
|
||||
{
|
||||
Task<PatientDto> CreateAsync(string trustedAccountId,CreatePatientRequest request,CancellationToken ct);
|
||||
Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest request,CancellationToken ct);
|
||||
Task<PatientDto> CreateAsync(string trustedAccountId, CreatePatientRequest request, CancellationToken ct);
|
||||
Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope, UpdatePatientRequest request, CancellationToken ct);
|
||||
}
|
||||
public sealed class ProfileAlreadyExistsException : Exception;
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
// Bundle metadata, not an additional patient response or a clinical decision algorithm.
|
||||
public sealed record ClinicalRuleProvenance(string Metric, string Claim,
|
||||
string Prerequisites, string AllowedInference, string ReviewState);
|
||||
@@ -1,6 +1,7 @@
|
||||
namespace HealthApp.Contracts;
|
||||
public sealed record HealthOverviewDto(PatientDto Patient,ObservationDto? LatestObservation,HealthInsight? Insight,DateTime PeriodStart,DateTime PeriodEnd,ContextSelection InsightSelection,int InsightContributingCount,string LatestObservationBasis,string InsightExplanation);
|
||||
|
||||
public sealed record HealthOverviewDto(PatientDto Patient, ObservationDto? LatestObservation, HealthInsight? Insight, DateTime PeriodStart, DateTime PeriodEnd, ContextSelection InsightSelection, int InsightContributingCount, string LatestObservationBasis, string InsightExplanation);
|
||||
public interface OverviewQueries
|
||||
{
|
||||
Task<HealthOverviewDto?> GetAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
|
||||
Task<HealthOverviewDto?> GetAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct);
|
||||
}
|
||||
@@ -1,19 +1,20 @@
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public interface ObservationQueries
|
||||
{
|
||||
Task<Guid?> ResolveOwnerAsync(Guid observationId,CancellationToken ct);
|
||||
Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct);
|
||||
Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope,CancellationToken ct);
|
||||
Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
|
||||
Task<Guid?> ResolveOwnerAsync(Guid observationId, CancellationToken ct);
|
||||
Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope, Guid id, CancellationToken ct);
|
||||
Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope, CancellationToken ct);
|
||||
Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct);
|
||||
}
|
||||
public interface ObservationCommands
|
||||
{
|
||||
Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope,RecordObservationRequest request,CancellationToken ct);
|
||||
Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope,Guid id,PatchObservationRequest request,CancellationToken ct);
|
||||
Task<bool> DeleteAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct);
|
||||
Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope, RecordObservationRequest request, CancellationToken ct);
|
||||
Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope, Guid id, PatchObservationRequest request, CancellationToken ct);
|
||||
Task<bool> DeleteAsync(AuthorizedPatientContext scope, Guid id, CancellationToken ct);
|
||||
}
|
||||
public static class MeasurementPeriod
|
||||
{
|
||||
public static DateTime Normalize(DateTime t)=>DateTime.SpecifyKind(t.Kind==DateTimeKind.Unspecified?t:t.ToUniversalTime(),DateTimeKind.Unspecified);
|
||||
public static void Validate(DateTime from,DateTime to){if(Normalize(to)<Normalize(from))throw new ArgumentException("The end time must not be earlier than the start time.");}
|
||||
public static DateTime Normalize(DateTime t) => DateTime.SpecifyKind(t.Kind == DateTimeKind.Unspecified ? t : t.ToUniversalTime(), DateTimeKind.Unspecified);
|
||||
public static void Validate(DateTime from, DateTime to) { if (Normalize(to) < Normalize(from)) throw new ArgumentException("The end time must not be earlier than the start time."); }
|
||||
}
|
||||
@@ -5,30 +5,30 @@ namespace HealthApp.Infrastructure;
|
||||
// Coordinates mechanics only; it has no health table/query or access-policy knowledge.
|
||||
public sealed class RequestTransaction(NpgsqlDataSource source) : IAsyncDisposable
|
||||
{
|
||||
public NpgsqlConnection? Connection {get;private set;}
|
||||
public NpgsqlTransaction? Transaction {get;private set;}
|
||||
public bool Active=>Transaction is not null;
|
||||
public async Task BeginAsync(bool write,CancellationToken ct)
|
||||
{
|
||||
if(Active)return;
|
||||
Connection=await source.OpenConnectionAsync(ct);
|
||||
Transaction=await Connection.BeginTransactionAsync(write?IsolationLevel.ReadCommitted:IsolationLevel.RepeatableRead,ct);
|
||||
}
|
||||
public async Task EnlistAsync(DbContext context,CancellationToken ct)
|
||||
{
|
||||
if(Transaction is null || Connection is null)throw new InvalidOperationException("No request transaction.");
|
||||
if(context.Database.GetDbConnection()!=Connection)context.Database.SetDbConnection(Connection,false);
|
||||
await context.Database.UseTransactionAsync(Transaction,ct);
|
||||
}
|
||||
public async Task FinishAsync(CancellationToken ct)
|
||||
{
|
||||
if(Transaction is null)return;
|
||||
await Transaction.CommitAsync(ct);await Transaction.DisposeAsync();Transaction=null;
|
||||
await Connection!.DisposeAsync();Connection=null;
|
||||
}
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if(Transaction is not null){await Transaction.DisposeAsync();Transaction=null;}
|
||||
if(Connection is not null){await Connection.DisposeAsync();Connection=null;}
|
||||
}
|
||||
public NpgsqlConnection? Connection { get; private set; }
|
||||
public NpgsqlTransaction? Transaction { get; private set; }
|
||||
public bool Active => Transaction is not null;
|
||||
public async Task BeginAsync(bool write, CancellationToken ct)
|
||||
{
|
||||
if (Active) return;
|
||||
Connection = await source.OpenConnectionAsync(ct);
|
||||
Transaction = await Connection.BeginTransactionAsync(write ? IsolationLevel.ReadCommitted : IsolationLevel.RepeatableRead, ct);
|
||||
}
|
||||
public async Task EnlistAsync(DbContext context, CancellationToken ct)
|
||||
{
|
||||
if (Transaction is null || Connection is null) throw new InvalidOperationException("No request transaction.");
|
||||
if (context.Database.GetDbConnection() != Connection) context.Database.SetDbConnection(Connection, false);
|
||||
await context.Database.UseTransactionAsync(Transaction, ct);
|
||||
}
|
||||
public async Task FinishAsync(CancellationToken ct)
|
||||
{
|
||||
if (Transaction is null) return;
|
||||
await Transaction.CommitAsync(ct); await Transaction.DisposeAsync(); Transaction = null;
|
||||
await Connection!.DisposeAsync(); Connection = null;
|
||||
}
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Transaction is not null) { await Transaction.DisposeAsync(); Transaction = null; }
|
||||
if (Connection is not null) { await Connection.DisposeAsync(); Connection = null; }
|
||||
}
|
||||
}
|
||||
@@ -26,13 +26,20 @@ public sealed class AuthenticationController(PrototypeAccounts accounts,
|
||||
new Claim(ClaimTypes.Role, account.Role)
|
||||
}, "Bearer"));
|
||||
var settings = options.Get("Bearer");
|
||||
var expiry = settings.TimeProvider!.GetUtcNow().Add(settings.BearerTokenExpiration);
|
||||
var issued = settings.TimeProvider!.GetUtcNow();
|
||||
var expiry = issued.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");
|
||||
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { IssuedUtc = issued, 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 });
|
||||
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);
|
||||
|
||||
@@ -4,14 +4,15 @@ using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
namespace HealthApp.Controllers;
|
||||
|
||||
[ApiController]
|
||||
public sealed class HealthOverviewController(OverviewQueries overview,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
public sealed class HealthOverviewController(OverviewQueries overview, AccessPolicy access, RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/patients/{patientId:guid}/overview")]
|
||||
public async Task<IActionResult> Get(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null){Response.StatusCode=404;return new EmptyResult();}
|
||||
try{var o=await overview.GetAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);return o is null?Problem(statusCode:404,title:"Patient does not exist."):Ok(o);}
|
||||
catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
|
||||
}
|
||||
[HttpGet("api/patients/{patientId:guid}/overview")]
|
||||
public async Task<IActionResult> Get(Guid patientId, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, [FromQuery] ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
var scope = await access.AuthorizeAsync(User, patientId, false, ct); if (scope is null) { Response.StatusCode = 404; return new EmptyResult(); }
|
||||
try { var o = await overview.GetAsync(scope, from, to, selection, ct); await tx.FinishAsync(ct); return o is null ? Problem(statusCode: 404, title: "Patient does not exist.") : Ok(o); }
|
||||
catch (ArgumentException) { ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time."); return ValidationProblem(ModelState); }
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,18 @@ using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
namespace HealthApp.Controllers;
|
||||
|
||||
[ApiController]
|
||||
public sealed class InsightsController(AnalyticsQueries analytics,AccessPolicy access) : ControllerBase
|
||||
public sealed class InsightsController(AnalyticsQueries analytics, AccessPolicy access) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/patients/{patientId:guid}/insights")]
|
||||
public Task<IActionResult> Insight(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)=>Calculate(patientId,from,to,selection,false,ct);
|
||||
[HttpGet("api/patients/{patientId:guid}/trends")]
|
||||
public Task<IActionResult> Trend(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)=>Calculate(patientId,from,to,selection,true,ct);
|
||||
private async Task<IActionResult> Calculate(Guid patientId,DateTime from,DateTime to,ContextSelection selection,bool trend,CancellationToken ct)
|
||||
{
|
||||
var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null){Response.StatusCode=404;return new EmptyResult();}
|
||||
try{if(trend)return Ok(await analytics.TrendAsync(scope,from,to,selection,ct));var insight=await analytics.InsightAsync(scope,from,to,selection,ct);return insight is null?Problem(statusCode:404,title:"Insufficient observation data for calculation."):Ok(insight);}
|
||||
catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
|
||||
}
|
||||
[HttpGet("api/patients/{patientId:guid}/insights")]
|
||||
public Task<IActionResult> Insight(Guid patientId, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, [FromQuery] ContextSelection selection, CancellationToken ct) => Calculate(patientId, from, to, selection, false, ct);
|
||||
[HttpGet("api/patients/{patientId:guid}/trends")]
|
||||
public Task<IActionResult> Trend(Guid patientId, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, [FromQuery] ContextSelection selection, CancellationToken ct) => Calculate(patientId, from, to, selection, true, ct);
|
||||
private async Task<IActionResult> Calculate(Guid patientId, DateTime from, DateTime to, ContextSelection selection, bool trend, CancellationToken ct)
|
||||
{
|
||||
var scope = await access.AuthorizeAsync(User, patientId, false, ct); if (scope is null) { Response.StatusCode = 404; return new EmptyResult(); }
|
||||
try { if (trend) return Ok(await analytics.TrendAsync(scope, from, to, selection, ct)); var insight = await analytics.InsightAsync(scope, from, to, selection, ct); return insight is null ? Problem(statusCode: 404, title: "Insufficient observation data for calculation.") : Ok(insight); }
|
||||
catch (ArgumentException) { ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time."); return ValidationProblem(ModelState); }
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,14 @@ using HealthApp.Guidance;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
namespace HealthApp.Controllers;
|
||||
|
||||
[ApiController, AllowAnonymous, Route("api/measurement-guidance")]
|
||||
public sealed class MeasurementGuidanceController(GuidanceQueries guidance) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public IActionResult Get([FromQuery] string? setting, [FromQuery] string? activityCondition)
|
||||
{
|
||||
try { return Ok(guidance.Get(setting, activityCondition)); }
|
||||
catch (ArgumentException e) { return Problem(statusCode:400, title:e.Message); }
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult Get([FromQuery] string? setting, [FromQuery] string? activityCondition)
|
||||
{
|
||||
try { return Ok(guidance.Get(setting, activityCondition)); }
|
||||
catch (ArgumentException e) { return Problem(statusCode: 400, title: e.Message); }
|
||||
}
|
||||
}
|
||||
@@ -5,29 +5,30 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
namespace HealthApp.Controllers;
|
||||
[ApiController,Route("api")]
|
||||
public sealed class ObservationController(ObservationQueries queries,ObservationCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable(){Response.StatusCode=404;return new EmptyResult();}
|
||||
|
||||
private async Task<AuthorizedPatientContext?> Owner(Guid id,bool write,CancellationToken ct){var owner=await queries.ResolveOwnerAsync(id,ct);return owner is null?null:await access.AuthorizeAsync(User,owner.Value,write,ct);}
|
||||
[HttpPost("patients/{patientId:guid}/observations"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Record(Guid patientId,RecordObservationRequest r,CancellationToken ct){var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return Unavailable();var o=await commands.RecordAsync(scope,r,ct);await tx.FinishAsync(ct);return o is null?NotFound():Created($"/api/observations/{o.ObservationId}",o);}
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid observationId,CancellationToken ct){var scope=await Owner(observationId,false,ct);if(scope is null)return Unavailable();var o=await queries.GetAsync(scope,observationId,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpPut("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public Task<IActionResult> Put(Guid observationId,UpdateObservationRequest r,CancellationToken ct)=>Patch(observationId,new PatchObservationRequest{Systolic=r.Systolic,Diastolic=r.Diastolic,Pulse=r.Pulse},ct);
|
||||
[HttpPatch("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Patch(Guid observationId,PatchObservationRequest r,CancellationToken ct){var scope=await Owner(observationId,true,ct);if(scope is null)return Unavailable();var o=await commands.PatchAsync(scope,observationId,r,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpDelete("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Delete(Guid observationId,CancellationToken ct){var scope=await Owner(observationId,true,ct);if(scope is null)return Unavailable();var found=await commands.DeleteAsync(scope,observationId,ct);await tx.FinishAsync(ct);return found?NoContent():NotFound();}
|
||||
[HttpGet("patients/{patientId:guid}/observations/latest")]
|
||||
public async Task<IActionResult> Latest(Guid patientId,CancellationToken ct){var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();var o=await queries.LatestAsync(scope,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpGet("patients/{patientId:guid}/observations")]
|
||||
public async Task<IActionResult> History(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();
|
||||
try{var series=await queries.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);Response.Headers["X-Measurement-Setting"]=selection.Setting??"All";Response.Headers["X-Activity-Condition"]=selection.ActivityCondition??"All";return Ok(series);}
|
||||
catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
|
||||
}
|
||||
[ApiController, Route("api")]
|
||||
public sealed class ObservationController(ObservationQueries queries, ObservationCommands commands, AccessPolicy access, RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable() { Response.StatusCode = 404; return new EmptyResult(); }
|
||||
|
||||
private async Task<AuthorizedPatientContext?> Owner(Guid id, bool write, CancellationToken ct) { var owner = await queries.ResolveOwnerAsync(id, ct); return owner is null ? null : await access.AuthorizeAsync(User, owner.Value, write, ct); }
|
||||
[HttpPost("patients/{patientId:guid}/observations"), Authorize(Policy = "Patient")]
|
||||
public async Task<IActionResult> Record(Guid patientId, RecordObservationRequest r, CancellationToken ct) { var scope = await access.AuthorizeAsync(User, patientId, true, ct); if (scope is null) return Unavailable(); var o = await commands.RecordAsync(scope, r, ct); await tx.FinishAsync(ct); return o is null ? NotFound() : Created($"/api/observations/{o.ObservationId}", o); }
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid observationId, CancellationToken ct) { var scope = await Owner(observationId, false, ct); if (scope is null) return Unavailable(); var o = await queries.GetAsync(scope, observationId, ct); await tx.FinishAsync(ct); return o is null ? NotFound() : Ok(o); }
|
||||
[HttpPut("observations/{observationId:guid}"), Authorize(Policy = "Patient")]
|
||||
public Task<IActionResult> Put(Guid observationId, UpdateObservationRequest r, CancellationToken ct) => Patch(observationId, new PatchObservationRequest { Systolic = r.Systolic, Diastolic = r.Diastolic, Pulse = r.Pulse }, ct);
|
||||
[HttpPatch("observations/{observationId:guid}"), Authorize(Policy = "Patient")]
|
||||
public async Task<IActionResult> Patch(Guid observationId, PatchObservationRequest r, CancellationToken ct) { var scope = await Owner(observationId, true, ct); if (scope is null) return Unavailable(); var o = await commands.PatchAsync(scope, observationId, r, ct); await tx.FinishAsync(ct); return o is null ? NotFound() : Ok(o); }
|
||||
[HttpDelete("observations/{observationId:guid}"), Authorize(Policy = "Patient")]
|
||||
public async Task<IActionResult> Delete(Guid observationId, CancellationToken ct) { var scope = await Owner(observationId, true, ct); if (scope is null) return Unavailable(); var found = await commands.DeleteAsync(scope, observationId, ct); await tx.FinishAsync(ct); return found ? NoContent() : NotFound(); }
|
||||
[HttpGet("patients/{patientId:guid}/observations/latest")]
|
||||
public async Task<IActionResult> Latest(Guid patientId, CancellationToken ct) { var scope = await access.AuthorizeAsync(User, patientId, false, ct); if (scope is null) return Unavailable(); var o = await queries.LatestAsync(scope, ct); await tx.FinishAsync(ct); return o is null ? NotFound() : Ok(o); }
|
||||
[HttpGet("patients/{patientId:guid}/observations")]
|
||||
public async Task<IActionResult> History(Guid patientId, [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, [FromQuery] ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
var scope = await access.AuthorizeAsync(User, patientId, false, ct); if (scope is null) return Unavailable();
|
||||
try { var series = await queries.SelectedAsync(scope, from, to, selection, ct); await tx.FinishAsync(ct); Response.Headers["X-Measurement-Setting"] = selection.Setting ?? "All"; Response.Headers["X-Activity-Condition"] = selection.ActivityCondition ?? "All"; return Ok(series); }
|
||||
catch (ArgumentException) { ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time."); return ValidationProblem(ModelState); }
|
||||
}
|
||||
}
|
||||
@@ -5,27 +5,28 @@ using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
namespace HealthApp.Controllers;
|
||||
[ApiController,Route("api/patients")]
|
||||
public sealed class PatientController(ProfileQueries queries,ProfileCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable(){Response.StatusCode=404;return new EmptyResult();}
|
||||
|
||||
[HttpPost,Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Create(CreatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
try{var p=await commands.CreateAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!,r,ct);await tx.FinishAsync(ct);return Created($"/api/patients/{p.PatientId}",p);}
|
||||
catch(ProfileAlreadyExistsException){return Conflict(new{title="A profile already exists for this account."});}
|
||||
}
|
||||
[HttpGet("me"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Me(CancellationToken ct)
|
||||
{
|
||||
var id=await queries.ResolveAccountAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!,ct);if(id is null)return NotFound();
|
||||
var scope=await access.AuthorizeAsync(User,id.Value,false,ct);var p=await queries.GetAsync(scope!,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);
|
||||
}
|
||||
[HttpGet("{patientId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid patientId,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();var p=await queries.GetAsync(scope,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
[HttpPut("{patientId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Update(Guid patientId,UpdatePatientRequest r,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return Unavailable();var p=await commands.UpdateAsync(scope,r,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
[ApiController, Route("api/patients")]
|
||||
public sealed class PatientController(ProfileQueries queries, ProfileCommands commands, AccessPolicy access, RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable() { Response.StatusCode = 404; return new EmptyResult(); }
|
||||
|
||||
[HttpPost, Authorize(Policy = "Patient")]
|
||||
public async Task<IActionResult> Create(CreatePatientRequest r, CancellationToken ct)
|
||||
{
|
||||
try { var p = await commands.CreateAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!, r, ct); await tx.FinishAsync(ct); return Created($"/api/patients/{p.PatientId}", p); }
|
||||
catch (ProfileAlreadyExistsException) { return Conflict(new { title = "A profile already exists for this account." }); }
|
||||
}
|
||||
[HttpGet("me"), Authorize(Policy = "Patient")]
|
||||
public async Task<IActionResult> Me(CancellationToken ct)
|
||||
{
|
||||
var id = await queries.ResolveAccountAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!, ct); if (id is null) return NotFound();
|
||||
var scope = await access.AuthorizeAsync(User, id.Value, false, ct); var p = await queries.GetAsync(scope!, ct); await tx.FinishAsync(ct); return p is null ? NotFound() : Ok(p);
|
||||
}
|
||||
[HttpGet("{patientId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid patientId, CancellationToken ct)
|
||||
{ var scope = await access.AuthorizeAsync(User, patientId, false, ct); if (scope is null) return Unavailable(); var p = await queries.GetAsync(scope, ct); await tx.FinishAsync(ct); return p is null ? NotFound() : Ok(p); }
|
||||
[HttpPut("{patientId:guid}"), Authorize(Policy = "Patient")]
|
||||
public async Task<IActionResult> Update(Guid patientId, UpdatePatientRequest r, CancellationToken ct)
|
||||
{ var scope = await access.AuthorizeAsync(User, patientId, true, ct); if (scope is null) return Unavailable(); var p = await commands.UpdateAsync(scope, r, ct); await tx.FinishAsync(ct); return p is null ? NotFound() : Ok(p); }
|
||||
}
|
||||
+73
-63
@@ -11,69 +11,79 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||
namespace HealthApp;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore",LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.EntityFrameworkCore",LogLevel.None);
|
||||
builder.Services.AddControllers(o=>o.Filters.Add<ReleaseTransactionFilter>());
|
||||
builder.Services.AddSingleton<RequestAdmission>();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddSingleton<PrototypeAccounts>();
|
||||
builder.Services.AddSingleton<ProfessionalAssignments>();
|
||||
builder.Services.AddSingleton<GuidanceQueries>();builder.Services.AddSingleton<ReferenceCatalog,ReviewedReferenceCatalog>();builder.Services.AddAnalytics();builder.Services.AddOverview();
|
||||
builder.Services.AddSingleton(sp=> {
|
||||
var c=sp.GetRequiredService<IConfiguration>();
|
||||
var text=c.GetConnectionString("HealthDatabase");
|
||||
if(string.IsNullOrWhiteSpace(text))throw new InvalidOperationException("HealthDatabase connection is required.");
|
||||
var options=new NpgsqlConnectionStringBuilder(text){Pooling=true,MaxPoolSize=c.GetValue("Resources:MaxPoolSize",32)};
|
||||
var local=options.Host is "localhost" or "127.0.0.1" or "::1" || options.Host?.StartsWith('/')==true;
|
||||
if((c.GetValue("Database:Remote",false)||!local)&&options.SslMode!=SslMode.VerifyFull)throw new InvalidOperationException("Remote database requires verified TLS and hostname checking.");
|
||||
return NpgsqlDataSource.Create(options.ConnectionString);
|
||||
});
|
||||
builder.Services.AddScoped<RequestTransaction>();builder.Services.AddProfile();builder.Services.AddObservations();builder.Services.AddScoped<AccessPolicy>();
|
||||
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
|
||||
builder.Services.AddOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((o,c,l)=> {
|
||||
var keys=c["Authentication:KeyDirectory"];
|
||||
if(string.IsNullOrWhiteSpace(keys)) throw new InvalidOperationException("Authentication:KeyDirectory is required.");
|
||||
o.XmlRepository=new Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository(new DirectoryInfo(keys),l);
|
||||
});
|
||||
builder.Services.AddAuthentication("Bearer").AddBearerToken("Bearer",o=>o.BearerTokenExpiration=TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes",30)));
|
||||
builder.Services.AddAuthorization(o=> {
|
||||
o.FallbackPolicy=new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
|
||||
foreach(var role in new[]{"Patient","HealthcareProfessional"}) o.AddPolicy(role,p=>p.RequireRole(role).RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
|
||||
});
|
||||
var app=builder.Build();
|
||||
var lifetime=app.Configuration.GetValue("Authentication:TokenLifetimeMinutes",30);
|
||||
if(lifetime is <=0 or >1440)throw new InvalidOperationException("Invalid token lifetime.");
|
||||
if(string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"]))throw new InvalidOperationException("Authentication:KeyDirectory is required.");
|
||||
_=app.Services.GetRequiredService<RequestAdmission>();
|
||||
if(app.Configuration.GetValue("Resources:RequestDeadlineSeconds",30d)<=0)throw new InvalidOperationException("Request deadline must be positive.");
|
||||
if(!string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("HealthDatabase")))_=app.Services.GetRequiredService<NpgsqlDataSource>();
|
||||
_=app.Services.GetRequiredService<PrototypeAccounts>();
|
||||
_=app.Services.GetRequiredService<ProfessionalAssignments>();
|
||||
app.UseExceptionHandler();
|
||||
app.Use(async(ctx,next)=> {
|
||||
if(!app.Environment.IsDevelopment() && !ctx.Request.IsHttps){ctx.Response.StatusCode=400;return;}
|
||||
if(!ctx.Request.Path.StartsWithSegments("/api/measurement-guidance"))ctx.Response.Headers.CacheControl="no-store";
|
||||
await next(ctx);
|
||||
});
|
||||
app.UseAuthentication();app.UseAuthorization();
|
||||
app.UseMiddleware<RequestBoundaryMiddleware>();
|
||||
app.MapControllers();
|
||||
app.MapGet("/health/live",()=>Results.Ok(new{status="live"})).RequireAuthorization();
|
||||
app.MapGet("/health/ready",async (HttpContext ctx)=>{
|
||||
try{
|
||||
_=ctx.RequestServices.GetRequiredService<Microsoft.AspNetCore.DataProtection.IDataProtectionProvider>().CreateProtector("readiness").Protect("probe");
|
||||
var catalog=ctx.RequestServices.GetRequiredService<ReferenceCatalog>();
|
||||
if(string.IsNullOrWhiteSpace(catalog.Version))return Results.StatusCode(503);
|
||||
await using var connection=await ctx.RequestServices.GetRequiredService<NpgsqlDataSource>().OpenConnectionAsync(ctx.RequestAborted);
|
||||
await using var command=new NpgsqlCommand("SELECT (SELECT max(version) FROM profile.schema_version)=1 AND (SELECT max(version) FROM observations.schema_version)=1",connection);
|
||||
return await command.ExecuteScalarAsync(ctx.RequestAborted) is true?Results.Ok(new{status="ready"}):Results.StatusCode(503);
|
||||
}catch(NpgsqlException){return Results.StatusCode(503);}
|
||||
}).RequireAuthorization();
|
||||
await app.RunAsync();
|
||||
}
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var configurationFile = Environment.GetEnvironmentVariable("HEALTHAPP_CONFIGURATION_FILE");
|
||||
if (!string.IsNullOrWhiteSpace(configurationFile)) builder.Configuration.AddJsonFile(configurationFile, optional: false, reloadOnChange: false);
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.EntityFrameworkCore", LogLevel.None);
|
||||
builder.Services.AddControllers(o => o.Filters.Add<ReleaseTransactionFilter>());
|
||||
builder.Services.AddSingleton<RequestAdmission>();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddSingleton<PrototypeAccounts>();
|
||||
builder.Services.AddSingleton<ProfessionalAssignments>();
|
||||
builder.Services.AddSingleton<GuidanceQueries>(); builder.Services.AddSingleton<ReferenceCatalog, ReviewedReferenceCatalog>(); builder.Services.AddAnalytics(); builder.Services.AddOverview();
|
||||
builder.Services.AddSingleton(sp =>
|
||||
{
|
||||
var c = sp.GetRequiredService<IConfiguration>();
|
||||
var text = c.GetConnectionString("HealthDatabase");
|
||||
if (string.IsNullOrWhiteSpace(text)) throw new InvalidOperationException("HealthDatabase connection is required.");
|
||||
var options = new NpgsqlConnectionStringBuilder(text) { Pooling = true, MaxPoolSize = c.GetValue("Resources:MaxPoolSize", 32) };
|
||||
var local = options.Host is "localhost" or "127.0.0.1" or "::1" || options.Host?.StartsWith('/') == true;
|
||||
if ((c.GetValue("Database:Remote", false) || !local) && options.SslMode != SslMode.VerifyFull) throw new InvalidOperationException("Remote database requires verified TLS and hostname checking.");
|
||||
return NpgsqlDataSource.Create(options.ConnectionString);
|
||||
});
|
||||
builder.Services.AddScoped<RequestTransaction>(); builder.Services.AddProfile(); builder.Services.AddObservations(); builder.Services.AddScoped<AccessPolicy>();
|
||||
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
|
||||
builder.Services.AddOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((o, c, l) =>
|
||||
{
|
||||
var keys = c["Authentication:KeyDirectory"];
|
||||
if (string.IsNullOrWhiteSpace(keys)) throw new InvalidOperationException("Authentication:KeyDirectory is required.");
|
||||
o.XmlRepository = new Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository(new DirectoryInfo(keys), l);
|
||||
});
|
||||
builder.Services.AddAuthentication("Bearer").AddBearerToken("Bearer", o => o.BearerTokenExpiration = TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30)));
|
||||
builder.Services.AddAuthorization(o =>
|
||||
{
|
||||
o.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
|
||||
foreach (var role in new[] { "Patient", "HealthcareProfessional" }) o.AddPolicy(role, p => p.RequireRole(role).RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier));
|
||||
});
|
||||
var app = builder.Build();
|
||||
var lifetime = app.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30);
|
||||
if (lifetime is <= 0 or > 1440) throw new InvalidOperationException("Invalid token lifetime.");
|
||||
if (string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"])) throw new InvalidOperationException("Authentication:KeyDirectory is required.");
|
||||
_ = app.Services.GetRequiredService<RequestAdmission>();
|
||||
if (app.Configuration.GetValue("Resources:RequestDeadlineSeconds", 30d) <= 0) throw new InvalidOperationException("Request deadline must be positive.");
|
||||
if (!string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("HealthDatabase"))) _ = app.Services.GetRequiredService<NpgsqlDataSource>();
|
||||
_ = app.Services.GetRequiredService<PrototypeAccounts>();
|
||||
_ = app.Services.GetRequiredService<ProfessionalAssignments>();
|
||||
app.UseExceptionHandler();
|
||||
app.Use(async (ctx, next) =>
|
||||
{
|
||||
if (!app.Environment.IsDevelopment() && !ctx.Request.IsHttps) { ctx.Response.StatusCode = 400; return; }
|
||||
if (!ctx.Request.Path.StartsWithSegments("/api/measurement-guidance")) ctx.Response.Headers.CacheControl = "no-store";
|
||||
await next(ctx);
|
||||
});
|
||||
app.UseAuthentication(); app.UseAuthorization();
|
||||
app.UseMiddleware<RequestBoundaryMiddleware>();
|
||||
app.MapControllers();
|
||||
app.MapGet("/health/live", () => Results.Ok(new { status = "live" })).RequireAuthorization();
|
||||
app.MapGet("/health/ready", async (HttpContext ctx) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = ctx.RequestServices.GetRequiredService<Microsoft.AspNetCore.DataProtection.IDataProtectionProvider>().CreateProtector("readiness").Protect("probe");
|
||||
var catalog = ctx.RequestServices.GetRequiredService<ReferenceCatalog>();
|
||||
if (string.IsNullOrWhiteSpace(catalog.Version)) return Results.StatusCode(503);
|
||||
await using var connection = await ctx.RequestServices.GetRequiredService<NpgsqlDataSource>().OpenConnectionAsync(ctx.RequestAborted);
|
||||
await using var command = new NpgsqlCommand("SELECT (SELECT max(version) FROM profile.schema_version)=1 AND (SELECT max(version) FROM observations.schema_version)=1", connection);
|
||||
return await command.ExecuteScalarAsync(ctx.RequestAborted) is true ? Results.Ok(new { status = "ready" }) : Results.StatusCode(503);
|
||||
}
|
||||
catch (NpgsqlException) { return Results.StatusCode(503); }
|
||||
}).RequireAuthorization();
|
||||
await app.RunAsync();
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
using System.Security.Claims;
|
||||
using HealthApp.Contracts;
|
||||
namespace HealthApp.Security;
|
||||
public sealed class AccessPolicy(ProfileQueries profiles,ProfessionalAssignments assignments)
|
||||
|
||||
public sealed class AccessPolicy(ProfileQueries profiles, ProfessionalAssignments assignments)
|
||||
{
|
||||
public async Task<AuthorizedPatientContext?> AuthorizeAsync(ClaimsPrincipal user,Guid actualPatient,bool write,CancellationToken ct)
|
||||
{
|
||||
var account=user.FindFirstValue(ClaimTypes.NameIdentifier)!;
|
||||
bool allowed=user.IsInRole("HealthcareProfessional") ? !write&&assignments.IsAssigned(account,actualPatient) : user.IsInRole("Patient")&&await profiles.ResolveAccountAsync(account,ct)==actualPatient;
|
||||
return allowed?new AuthorizedPatientContext(actualPatient,write):null;
|
||||
}
|
||||
public async Task<AuthorizedPatientContext?> AuthorizeAsync(ClaimsPrincipal user, Guid actualPatient, bool write, CancellationToken ct)
|
||||
{
|
||||
var account = user.FindFirstValue(ClaimTypes.NameIdentifier)!;
|
||||
bool allowed = user.IsInRole("HealthcareProfessional") ? !write && assignments.IsAssigned(account, actualPatient) : user.IsInRole("Patient") && await profiles.ResolveAccountAsync(account, ct) == actualPatient;
|
||||
return allowed ? new AuthorizedPatientContext(actualPatient, write) : null;
|
||||
}
|
||||
}
|
||||
@@ -4,68 +4,69 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Npgsql;
|
||||
namespace HealthApp.Security;
|
||||
|
||||
public sealed class RequestAdmission(IConfiguration configuration) : IDisposable
|
||||
{
|
||||
public SemaphoreSlim Health {get;}=new(Positive(configuration,"Resources:MaxConcurrentRequests",32));
|
||||
public SemaphoreSlim Assessment {get;}=new(Positive(configuration,"Resources:MaxConcurrentAssessments",4));
|
||||
private static int Positive(IConfiguration c,string key,int fallback)
|
||||
{var value=c.GetValue(key,fallback);return value>0?value:throw new InvalidOperationException(key+" must be positive.");}
|
||||
public void Dispose(){Health.Dispose();Assessment.Dispose();}
|
||||
public SemaphoreSlim Health { get; } = new(Positive(configuration, "Resources:MaxConcurrentRequests", 32));
|
||||
public SemaphoreSlim Assessment { get; } = new(Positive(configuration, "Resources:MaxConcurrentAssessments", 4));
|
||||
private static int Positive(IConfiguration c, string key, int fallback)
|
||||
{ var value = c.GetValue(key, fallback); return value > 0 ? value : throw new InvalidOperationException(key + " must be positive."); }
|
||||
public void Dispose() { Health.Dispose(); Assessment.Dispose(); }
|
||||
}
|
||||
public sealed class ReleaseTransactionFilter : IAsyncActionFilter
|
||||
{
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context,ActionExecutionDelegate next)
|
||||
{
|
||||
try{await next();}
|
||||
finally{if(context.HttpContext.Items[typeof(RequestTransaction)] is RequestTransaction tx && tx.Active)await tx.DisposeAsync();}
|
||||
}
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
try { await next(); }
|
||||
finally { if (context.HttpContext.Items[typeof(RequestTransaction)] is RequestTransaction tx && tx.Active) await tx.DisposeAsync(); }
|
||||
}
|
||||
}
|
||||
public sealed class RequestBoundaryMiddleware(RequestDelegate next,RequestAdmission admission,IConfiguration configuration,ILogger<RequestBoundaryMiddleware> logger)
|
||||
public sealed class RequestBoundaryMiddleware(RequestDelegate next, RequestAdmission admission, IConfiguration configuration, ILogger<RequestBoundaryMiddleware> logger)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext ctx)
|
||||
{
|
||||
if(ctx.GetEndpoint() is null || ctx.GetEndpoint()!.Metadata.GetMetadata<IAllowAnonymous>() is not null || ctx.Request.Path.StartsWithSegments("/api/professionals") || ctx.Request.Path.StartsWithSegments("/health")){await next(ctx);return;}
|
||||
if(ctx.User.Identity?.IsAuthenticated!=true){await next(ctx);return;}
|
||||
if(!ctx.User.IsInRole("Patient")&&!ctx.User.IsInRole("HealthcareProfessional")){ctx.Response.StatusCode=403;return;}
|
||||
if(ctx.User.IsInRole("HealthcareProfessional")&&ctx.Request.Method!="GET"){ctx.Response.StatusCode=403;return;}
|
||||
var assessment=ctx.Request.RouteValues["controller"]?.ToString() is "Insights" or "HealthOverview";
|
||||
if(!await admission.Health.WaitAsync(0,ctx.RequestAborted)){await Overloaded(ctx);return;}
|
||||
var assessmentHeld=false;
|
||||
var parent=ctx.RequestAborted;
|
||||
using var deadline=CancellationTokenSource.CreateLinkedTokenSource(parent);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(configuration.GetValue("Resources:RequestDeadlineSeconds",30d)));
|
||||
ctx.RequestAborted=deadline.Token;
|
||||
RequestTransaction? tx=null;
|
||||
try
|
||||
{
|
||||
if(assessment){assessmentHeld=await admission.Assessment.WaitAsync(0,deadline.Token);if(!assessmentHeld){await Overloaded(ctx);return;}}
|
||||
tx=ctx.RequestServices.GetRequiredService<RequestTransaction>();ctx.Items[typeof(RequestTransaction)]=tx;
|
||||
var write=ctx.Request.Method!="GET";await tx.BeginAsync(write,deadline.Token);
|
||||
Guid? actual=null;
|
||||
if(Guid.TryParse(ctx.Request.RouteValues["patientId"]?.ToString(),out var patient))actual=patient;
|
||||
else if(Guid.TryParse(ctx.Request.RouteValues["observationId"]?.ToString(),out var observation))actual=await ctx.RequestServices.GetRequiredService<ObservationQueries>().ResolveOwnerAsync(observation,deadline.Token);
|
||||
if(ctx.Request.RouteValues.ContainsKey("patientId")||ctx.Request.RouteValues.ContainsKey("observationId"))
|
||||
{
|
||||
var scope=actual is null?null:await ctx.RequestServices.GetRequiredService<AccessPolicy>().AuthorizeAsync(ctx.User,actual.Value,write,deadline.Token);
|
||||
if(scope is null){ctx.Response.StatusCode=404;return;}
|
||||
}
|
||||
await next(ctx);
|
||||
}
|
||||
catch(OperationCanceledException) when(parent.IsCancellationRequested){ctx.Abort();}
|
||||
catch(OperationCanceledException){ctx.RequestAborted=parent;await Failure(ctx,504);}
|
||||
catch(NpgsqlException e){ctx.RequestAborted=parent;await Failure(ctx,e.InnerException is TimeoutException?504:503);}
|
||||
finally
|
||||
{
|
||||
if(tx is not null)await tx.DisposeAsync();ctx.RequestAborted=parent;
|
||||
if(assessmentHeld)admission.Assessment.Release();admission.Health.Release();
|
||||
}
|
||||
}
|
||||
private Task Failure(HttpContext ctx,int status)
|
||||
{
|
||||
logger.LogWarning("Operation {Operation} failed with {Status}; correlation {Correlation}",ctx.Request.RouteValues["action"],status,ctx.TraceIdentifier);
|
||||
if(ctx.Response.HasStarted){ctx.Abort();return Task.CompletedTask;}
|
||||
ctx.Response.Clear();ctx.Response.Headers.CacheControl="no-store";
|
||||
return Results.Problem(statusCode:status,title:status==504?"Request deadline reached.":"Health data dependency is unavailable.").ExecuteAsync(ctx);
|
||||
}
|
||||
private static Task Overloaded(HttpContext ctx){ctx.Response.Headers.RetryAfter="1";ctx.Response.Headers.CacheControl="no-store";return Results.Problem(statusCode:503,title:"Request capacity is unavailable.").ExecuteAsync(ctx);}
|
||||
public async Task InvokeAsync(HttpContext ctx)
|
||||
{
|
||||
if (ctx.GetEndpoint() is null || ctx.GetEndpoint()!.Metadata.GetMetadata<IAllowAnonymous>() is not null || ctx.Request.Path.StartsWithSegments("/api/professionals") || ctx.Request.Path.StartsWithSegments("/health")) { await next(ctx); return; }
|
||||
if (ctx.User.Identity?.IsAuthenticated != true) { await next(ctx); return; }
|
||||
if (!ctx.User.IsInRole("Patient") && !ctx.User.IsInRole("HealthcareProfessional")) { ctx.Response.StatusCode = 403; return; }
|
||||
if (ctx.User.IsInRole("HealthcareProfessional") && ctx.Request.Method != "GET") { ctx.Response.StatusCode = 403; return; }
|
||||
var assessment = ctx.Request.RouteValues["controller"]?.ToString() is "Insights" or "HealthOverview";
|
||||
if (!await admission.Health.WaitAsync(0, ctx.RequestAborted)) { await Overloaded(ctx); return; }
|
||||
var assessmentHeld = false;
|
||||
var parent = ctx.RequestAborted;
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(parent);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(configuration.GetValue("Resources:RequestDeadlineSeconds", 30d)));
|
||||
ctx.RequestAborted = deadline.Token;
|
||||
RequestTransaction? tx = null;
|
||||
try
|
||||
{
|
||||
if (assessment) { assessmentHeld = await admission.Assessment.WaitAsync(0, deadline.Token); if (!assessmentHeld) { await Overloaded(ctx); return; } }
|
||||
tx = ctx.RequestServices.GetRequiredService<RequestTransaction>(); ctx.Items[typeof(RequestTransaction)] = tx;
|
||||
var write = ctx.Request.Method != "GET"; await tx.BeginAsync(write, deadline.Token);
|
||||
Guid? actual = null;
|
||||
if (Guid.TryParse(ctx.Request.RouteValues["patientId"]?.ToString(), out var patient)) actual = patient;
|
||||
else if (Guid.TryParse(ctx.Request.RouteValues["observationId"]?.ToString(), out var observation)) actual = await ctx.RequestServices.GetRequiredService<ObservationQueries>().ResolveOwnerAsync(observation, deadline.Token);
|
||||
if (ctx.Request.RouteValues.ContainsKey("patientId") || ctx.Request.RouteValues.ContainsKey("observationId"))
|
||||
{
|
||||
var scope = actual is null ? null : await ctx.RequestServices.GetRequiredService<AccessPolicy>().AuthorizeAsync(ctx.User, actual.Value, write, deadline.Token);
|
||||
if (scope is null) { ctx.Response.StatusCode = 404; return; }
|
||||
}
|
||||
await next(ctx);
|
||||
}
|
||||
catch (OperationCanceledException) when (parent.IsCancellationRequested) { ctx.Abort(); }
|
||||
catch (OperationCanceledException) { ctx.RequestAborted = parent; await Failure(ctx, 504); }
|
||||
catch (NpgsqlException e) { ctx.RequestAborted = parent; await Failure(ctx, e.InnerException is TimeoutException ? 504 : 503); }
|
||||
finally
|
||||
{
|
||||
if (tx is not null) await tx.DisposeAsync(); ctx.RequestAborted = parent;
|
||||
if (assessmentHeld) admission.Assessment.Release(); admission.Health.Release();
|
||||
}
|
||||
}
|
||||
private Task Failure(HttpContext ctx, int status)
|
||||
{
|
||||
logger.LogWarning("Operation {Operation} failed with {Status}; correlation {Correlation}", ctx.Request.RouteValues["action"], status, ctx.TraceIdentifier);
|
||||
if (ctx.Response.HasStarted) { ctx.Abort(); return Task.CompletedTask; }
|
||||
ctx.Response.Clear(); ctx.Response.Headers.CacheControl = "no-store";
|
||||
return Results.Problem(statusCode: status, title: status == 504 ? "Request deadline reached." : "Health data dependency is unavailable.").ExecuteAsync(ctx);
|
||||
}
|
||||
private static Task Overloaded(HttpContext ctx) { ctx.Response.Headers.RetryAfter = "1"; ctx.Response.Headers.CacheControl = "no-store"; return Results.Problem(statusCode: 503, title: "Request capacity is unavailable.").ExecuteAsync(ctx); }
|
||||
}
|
||||
@@ -2,24 +2,33 @@ using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
namespace HealthApp.Analytics;
|
||||
internal sealed class AnalyticsFacade(ObservationQueries observations,RequestTransaction tx,SummaryPolicy summary,TrendPolicy trend) : AnalyticsQueries
|
||||
|
||||
internal sealed class AnalyticsFacade(ObservationQueries observations, RequestTransaction tx, SummaryPolicy summary, TrendPolicy trend) : AnalyticsQueries
|
||||
{
|
||||
public async Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return summary.CalculateSummary(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
|
||||
public async Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return trend.CalculateTrend(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
|
||||
public async Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
var series = await observations.SelectedAsync(scope, from, to, selection, ct); await tx.FinishAsync(ct); ct.ThrowIfCancellationRequested(); var result = summary.CalculateSummary(scope.PatientId, MeasurementPeriod.Normalize(from), MeasurementPeriod.Normalize(to), series, selection);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return result;
|
||||
}
|
||||
public async Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
var series = await observations.SelectedAsync(scope, from, to, selection, ct); await tx.FinishAsync(ct); ct.ThrowIfCancellationRequested(); var result = trend.CalculateTrend(scope.PatientId, MeasurementPeriod.Normalize(from), MeasurementPeriod.Normalize(to), series, selection);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public static class AnalyticsModule
|
||||
{
|
||||
public static IServiceCollection AddAnalytics(this IServiceCollection s)
|
||||
{s.AddSingleton<SummaryPolicy>();s.AddSingleton<ClinicalPolicy>();s.AddSingleton<TrendPolicy>();s.AddScoped<AnalyticsQueries,AnalyticsFacade>();return s;}
|
||||
public static IServiceCollection AddAnalytics(this IServiceCollection s)
|
||||
{ s.AddSingleton<SummaryPolicy>(); s.AddSingleton<ClinicalPolicy>(); s.AddSingleton<TrendPolicy>(); s.AddScoped<AnalyticsQueries, AnalyticsFacade>(); return s; }
|
||||
}
|
||||
// Test-only-compatible calculation entry, internal to the module; no public repository/SQL access.
|
||||
internal sealed class InsightCalculator
|
||||
{
|
||||
private readonly SummaryPolicy summary=new();
|
||||
private readonly TrendPolicy trend;
|
||||
internal InsightCalculator(ReferenceCatalog catalog){trend=new(new ClinicalPolicy(catalog));}
|
||||
public HealthInsight? CalculateSummary(Guid patientId,DateTime from,DateTime to,IReadOnlyList<ObservationDto> observations,ContextSelection selection)=>summary.CalculateSummary(patientId,from,to,observations,selection);
|
||||
public TrendAssessment CalculateTrend(Guid patientId,DateTime from,DateTime to,IReadOnlyList<ObservationDto> observations,ContextSelection selection)=>trend.CalculateTrend(patientId,from,to,observations,selection);
|
||||
private readonly SummaryPolicy summary = new();
|
||||
private readonly TrendPolicy trend;
|
||||
internal InsightCalculator(ReferenceCatalog catalog) { trend = new(new ClinicalPolicy(catalog)); }
|
||||
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to, IReadOnlyList<ObservationDto> observations, ContextSelection selection) => summary.CalculateSummary(patientId, from, to, observations, selection);
|
||||
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to, IReadOnlyList<ObservationDto> observations, ContextSelection selection) => trend.CalculateTrend(patientId, from, to, observations, selection);
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
[assembly: InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -1,14 +1,15 @@
|
||||
using System.Globalization;
|
||||
using HealthApp.Contracts;
|
||||
namespace HealthApp.Analytics;
|
||||
|
||||
internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
|
||||
{
|
||||
internal 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.";
|
||||
|
||||
internal (ClinicalReference? Reference,string Comparison,string Interpretation,string Hint) Apply(string metric,string unit,IReadOnlyList<ObservationDto> observations,ComparabilityAssessment comparability,(DateTime Time,decimal Value)[] points,string direction,int reversals,decimal mean,Func<ObservationDto,int> value)
|
||||
{
|
||||
internal (ClinicalReference? Reference, string Comparison, string Interpretation, string Hint) Apply(string metric, string unit, IReadOnlyList<ObservationDto> observations, ComparabilityAssessment comparability, (DateTime Time, decimal Value)[] points, string direction, int reversals, decimal mean, Func<ObservationDto, int> value)
|
||||
{
|
||||
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.";
|
||||
@@ -64,8 +65,8 @@ internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
|
||||
"missing or differing conditions limit interpretation of the combined trajectory. ") +
|
||||
"An outside-reference value is not dismissed because preparation information is incomplete.";
|
||||
}
|
||||
return (reference,comparison,interpretation,hint);
|
||||
}
|
||||
return (reference, comparison, interpretation, hint);
|
||||
}
|
||||
private ClinicalReference? SelectReference(string metric, IReadOnlyList<ObservationDto> observations,
|
||||
ComparabilityAssessment comparability)
|
||||
{
|
||||
@@ -79,7 +80,7 @@ internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
|
||||
if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
|
||||
!new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
|
||||
return null;
|
||||
return catalog.Pressure(metric,settings[0]!);
|
||||
return catalog.Pressure(metric, settings[0]!);
|
||||
}
|
||||
|
||||
private static bool IsHigh(decimal value, ClinicalReference reference) =>
|
||||
|
||||
@@ -5,7 +5,8 @@ namespace HealthApp.Analytics;
|
||||
|
||||
internal sealed class TrendPolicy(ClinicalPolicy clinical)
|
||||
{
|
||||
private const string GeneralLimits=ClinicalPolicy.GeneralLimits;
|
||||
internal const string MethodVersion = "baseline-2026-10-05";
|
||||
private const string GeneralLimits = ClinicalPolicy.GeneralLimits;
|
||||
|
||||
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
|
||||
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
||||
@@ -62,8 +63,8 @@ internal sealed class TrendPolicy(ClinicalPolicy clinical)
|
||||
$"Total successive change is {Format(totalChange!.Value)} {unit}.") +
|
||||
" Range and successive change describe observed variation; no clinical stability classification is made.";
|
||||
|
||||
var result = clinical.Apply(metric,unit,observations,comparability,points,direction,reversals,mean,value);
|
||||
var reference=result.Reference;var comparison=result.Comparison;var interpretation=result.Interpretation;var hint=result.Hint;
|
||||
var result = clinical.Apply(metric, unit, observations, comparability, points, direction, reversals, mean, value);
|
||||
var reference = result.Reference; var comparison = result.Comparison; var interpretation = result.Interpretation; var hint = result.Hint;
|
||||
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,
|
||||
|
||||
@@ -3,6 +3,7 @@ namespace HealthApp.Guidance;
|
||||
// Content preserved from the pinned baseline; no new clinical review is implied.
|
||||
public sealed class GuidanceQueries
|
||||
{
|
||||
public const string Version = "baseline-2026-10-04";
|
||||
public object Get(string? setting, string? activityCondition)
|
||||
{
|
||||
var requestedSetting = string.IsNullOrWhiteSpace(setting) ? "Unknown" : setting.Trim();
|
||||
|
||||
@@ -3,21 +3,36 @@ namespace HealthApp.Guidance;
|
||||
// Pinned content and thresholds; this relocation does not imply a new clinical review.
|
||||
public sealed class ReviewedReferenceCatalog : ReferenceCatalog
|
||||
{
|
||||
public string Version=>"baseline-2026-10-05";
|
||||
public ClinicalReference Pulse()
|
||||
{
|
||||
return new("Recorded resting pulse", 50, "<", 100, ">",
|
||||
[new("Patienthåndbogen: Bradykardi (langsom puls)",
|
||||
public string Version => "baseline-2026-10-05";
|
||||
public IReadOnlyList<ClinicalRuleProvenance> Claims { get; } = Array.AsReadOnly(new[]
|
||||
{
|
||||
new ClinicalRuleProvenance("Systolic/Diastolic", "Setting-specific reference comparison",
|
||||
"All recorded AtRest, one Home/Clinic setting, no detected conflicts; recorded rest below five minutes or non-seated position blocks the comparison",
|
||||
"Compare raw levels with the cited inclusive high boundary; missing irrelevant optional detail does not suppress provisional comparison; no individual target or diagnosis",
|
||||
"Baseline sources reviewed 2026-10-05; no new clinical review"),
|
||||
new ClinicalRuleProvenance("Pulse", "Resting rate reference comparison",
|
||||
"All recorded AtRest and no detected narrative conflicts; BP-specific preparation does not gate pulse",
|
||||
"Compare raw resting rates below 50 or above 100 using exclusive limits; no rhythm diagnosis or universal healthy range",
|
||||
"Baseline sources reviewed 2026-10-05; no new clinical review"),
|
||||
new ClinicalRuleProvenance("Systolic/Diastolic/Pulse", "Development classification",
|
||||
"At least two distinct instants, applicable reference, SupportedRecordedComparability; exact preserved ClinicalPolicy branches govern reversals and opposite-boundary excursions",
|
||||
"Only the baseline PotentiallyFavourable/PotentiallyConcerning/Mixed/CannotInterpret branches; no blanket interpretation from numerical sign or range",
|
||||
"Preserved cautious baseline inference; independent domain validity remains unverified")
|
||||
});
|
||||
public ClinicalReference 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.");
|
||||
}
|
||||
public ClinicalReference Pressure(string metric,string setting)
|
||||
{
|
||||
"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.");
|
||||
}
|
||||
public ClinicalReference Pressure(string metric, string setting)
|
||||
{
|
||||
var threshold = metric == "Systolic" ? (setting == "Home" ? 135 : 140) :
|
||||
(setting == "Home" ? 85 : 90);
|
||||
return new($"Recorded {setting} resting blood pressure", null, null, threshold, ">=",
|
||||
@@ -27,5 +42,5 @@ public sealed class ReviewedReferenceCatalog : ReferenceCatalog
|
||||
"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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
[assembly: InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -6,34 +6,35 @@ using HealthApp.Observations.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
namespace HealthApp.Observations;
|
||||
internal sealed class ObservationFacade(ObservationDbContext db,RequestTransaction tx,ProfileQueries profiles) : ObservationQueries,ObservationCommands
|
||||
|
||||
internal sealed class ObservationFacade(ObservationDbContext db, RequestTransaction tx, ProfileQueries profiles) : ObservationQueries, ObservationCommands
|
||||
{
|
||||
public async Task<Guid?> ResolveOwnerAsync(Guid id,CancellationToken ct){await tx.EnlistAsync(db,ct);return await db.Observations.AsNoTracking().Where(o=>o.ObservationId==id).Select(o=>(Guid?)o.PatientId).SingleOrDefaultAsync(ct);}
|
||||
public async Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct){await tx.EnlistAsync(db,ct);var o=await db.Observations.AsNoTracking().SingleOrDefaultAsync(o=>o.ObservationId==id&&o.PatientId==scope.PatientId,ct);return o is null?null:Dto(o);}
|
||||
public async Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope,CancellationToken ct){await tx.EnlistAsync(db,ct);var o=await db.Observations.AsNoTracking().Where(o=>o.PatientId==scope.PatientId).OrderByDescending(o=>o.MeasuredAt).ThenByDescending(o=>o.CreatedAt).ThenByDescending(o=>o.ObservationId).FirstOrDefaultAsync(ct);return o is null?null:Dto(o);}
|
||||
public async Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
from=MeasurementPeriod.Normalize(from);to=MeasurementPeriod.Normalize(to);MeasurementPeriod.Validate(from,to);Validator.ValidateObject(selection,new ValidationContext(selection),true);await tx.EnlistAsync(db,ct);
|
||||
var q=db.Observations.AsNoTracking().Where(o=>o.PatientId==scope.PatientId&&o.MeasuredAt>=from&&o.MeasuredAt<=to);
|
||||
if(selection.Setting is not null)q=q.Where(o=>o.MeasurementContext.Setting==selection.Setting);
|
||||
if(selection.ActivityCondition is not null)q=q.Where(o=>o.MeasurementContext.ActivityCondition==selection.ActivityCondition);
|
||||
return Array.AsReadOnly((await q.OrderBy(o=>o.MeasuredAt).ThenBy(o=>o.ObservationId).ToListAsync(ct)).Select(Dto).ToArray());
|
||||
}
|
||||
public async Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope,RecordObservationRequest request,CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite();Validator.ValidateObject(request,new ValidationContext(request),true);
|
||||
var context=request.MeasurementContext??new();context=context with{Setting=context.Setting??"Unknown",ActivityCondition=context.ActivityCondition??"Unknown"};Validator.ValidateObject(context,new ValidationContext(context),true);
|
||||
if(await profiles.GetAsync(scope,ct) is null)return null;await tx.EnlistAsync(db,ct);
|
||||
var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
var o=new BloodPressureObservation{ObservationId=Guid.NewGuid(),PatientId=scope.PatientId,MeasuredAt=MeasurementPeriod.Normalize(request.MeasuredAt!.Value),Systolic=request.Systolic!.Value,Diastolic=request.Diastolic!.Value,Pulse=request.Pulse!.Value,MeasurementContext=context,Context=request.Context,Note=request.Note,CreatedAt=now,UpdatedAt=now};db.Observations.Add(o);await db.SaveChangesAsync(ct);return Dto(o);
|
||||
}
|
||||
private async Task<BloodPressureObservation?> LockedAsync(AuthorizedPatientContext scope,Guid id,CancellationToken cancellationToken)
|
||||
{scope.RequireWrite();await tx.EnlistAsync(db,cancellationToken);return await db.Observations.FromSqlInterpolated($"SELECT * FROM observations.observation WHERE observation_id={id} AND patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(cancellationToken);}
|
||||
public async Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope,Guid id,PatchObservationRequest request,CancellationToken cancellationToken)
|
||||
{
|
||||
Validator.ValidateObject(request,new ValidationContext(request),true);if(request.MeasurementContext is not null)Validator.ValidateObject(request.MeasurementContext,new ValidationContext(request.MeasurementContext),true);
|
||||
var observation=await LockedAsync(scope,id,cancellationToken);if(observation is null)return null;
|
||||
var updatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
public async Task<Guid?> ResolveOwnerAsync(Guid id, CancellationToken ct) { await tx.EnlistAsync(db, ct); return await db.Observations.AsNoTracking().Where(o => o.ObservationId == id).Select(o => (Guid?)o.PatientId).SingleOrDefaultAsync(ct); }
|
||||
public async Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope, Guid id, CancellationToken ct) { await tx.EnlistAsync(db, ct); var o = await db.Observations.AsNoTracking().SingleOrDefaultAsync(o => o.ObservationId == id && o.PatientId == scope.PatientId, ct); return o is null ? null : Dto(o); }
|
||||
public async Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope, CancellationToken ct) { await tx.EnlistAsync(db, ct); var o = await db.Observations.AsNoTracking().Where(o => o.PatientId == scope.PatientId).OrderByDescending(o => o.MeasuredAt).ThenByDescending(o => o.CreatedAt).ThenByDescending(o => o.ObservationId).FirstOrDefaultAsync(ct); return o is null ? null : Dto(o); }
|
||||
public async Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
from = MeasurementPeriod.Normalize(from); to = MeasurementPeriod.Normalize(to); MeasurementPeriod.Validate(from, to); Validator.ValidateObject(selection, new ValidationContext(selection), true); await tx.EnlistAsync(db, ct);
|
||||
var q = db.Observations.AsNoTracking().Where(o => o.PatientId == scope.PatientId && o.MeasuredAt >= from && o.MeasuredAt <= to);
|
||||
if (selection.Setting is not null) q = q.Where(o => o.MeasurementContext.Setting == selection.Setting);
|
||||
if (selection.ActivityCondition is not null) q = q.Where(o => o.MeasurementContext.ActivityCondition == selection.ActivityCondition);
|
||||
return Array.AsReadOnly((await q.OrderBy(o => o.MeasuredAt).ThenBy(o => o.ObservationId).ToListAsync(ct)).Select(Dto).ToArray());
|
||||
}
|
||||
public async Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope, RecordObservationRequest request, CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite(); Validator.ValidateObject(request, new ValidationContext(request), true);
|
||||
var context = request.MeasurementContext ?? new(); context = context with { Setting = context.Setting ?? "Unknown", ActivityCondition = context.ActivityCondition ?? "Unknown" }; Validator.ValidateObject(context, new ValidationContext(context), true);
|
||||
if (await profiles.GetAsync(scope, ct) is null) return null; await tx.EnlistAsync(db, ct);
|
||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
var o = new BloodPressureObservation { ObservationId = Guid.NewGuid(), PatientId = scope.PatientId, MeasuredAt = MeasurementPeriod.Normalize(request.MeasuredAt!.Value), Systolic = request.Systolic!.Value, Diastolic = request.Diastolic!.Value, Pulse = request.Pulse!.Value, MeasurementContext = context, Context = request.Context, Note = request.Note, CreatedAt = now, UpdatedAt = now }; db.Observations.Add(o); await db.SaveChangesAsync(ct); return Dto(o);
|
||||
}
|
||||
private async Task<BloodPressureObservation?> LockedAsync(AuthorizedPatientContext scope, Guid id, CancellationToken cancellationToken)
|
||||
{ scope.RequireWrite(); await tx.EnlistAsync(db, cancellationToken); return await db.Observations.FromSqlInterpolated($"SELECT * FROM observations.observation WHERE observation_id={id} AND patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(cancellationToken); }
|
||||
public async Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope, Guid id, PatchObservationRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Validator.ValidateObject(request, new ValidationContext(request), true); if (request.MeasurementContext is not null) Validator.ValidateObject(request.MeasurementContext, new ValidationContext(request.MeasurementContext), true);
|
||||
var observation = await LockedAsync(scope, id, cancellationToken); if (observation is null) return null;
|
||||
var updatedAt = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
if (request.SystolicSpecified) observation.Systolic = request.Systolic!.Value;
|
||||
if (request.DiastolicSpecified) observation.Diastolic = request.Diastolic!.Value;
|
||||
if (request.PulseSpecified) observation.Pulse = request.Pulse!.Value;
|
||||
@@ -61,17 +62,17 @@ internal sealed class ObservationFacade(ObservationDbContext db,RequestTransacti
|
||||
}
|
||||
observation.UpdatedAt = updatedAt;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return Dto(observation);
|
||||
}
|
||||
public async Task<bool> DeleteAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct)
|
||||
{var o=await LockedAsync(scope,id,ct);if(o is null)return false;db.Observations.Remove(o);await db.SaveChangesAsync(ct);return true;}
|
||||
private static ObservationDto Dto(BloodPressureObservation o)=>new(o.ObservationId,o.PatientId,o.MeasuredAt,o.Systolic,o.Diastolic,o.Pulse,new MeasurementContextDto(o.MeasurementContext.Setting,o.MeasurementContext.ActivityCondition,o.MeasurementContext.RestDurationMinutes,o.MeasurementContext.BodyPosition,o.MeasurementContext.MeasuredArm,o.MeasurementContext.DeviceDetails,o.MeasurementContext.CuffDetails,o.MeasurementContext.AdditionalCircumstances),o.Context,o.Note);
|
||||
return Dto(observation);
|
||||
}
|
||||
public async Task<bool> DeleteAsync(AuthorizedPatientContext scope, Guid id, CancellationToken ct)
|
||||
{ var o = await LockedAsync(scope, id, ct); if (o is null) return false; db.Observations.Remove(o); await db.SaveChangesAsync(ct); return true; }
|
||||
private static ObservationDto Dto(BloodPressureObservation o) => new(o.ObservationId, o.PatientId, o.MeasuredAt, o.Systolic, o.Diastolic, o.Pulse, new MeasurementContextDto(o.MeasurementContext.Setting, o.MeasurementContext.ActivityCondition, o.MeasurementContext.RestDurationMinutes, o.MeasurementContext.BodyPosition, o.MeasurementContext.MeasuredArm, o.MeasurementContext.DeviceDetails, o.MeasurementContext.CuffDetails, o.MeasurementContext.AdditionalCircumstances), o.Context, o.Note);
|
||||
}
|
||||
public static class ObservationsModule
|
||||
{
|
||||
public static IServiceCollection AddObservations(this IServiceCollection s)
|
||||
{
|
||||
s.AddScoped(sp=>new ObservationDbContext(new DbContextOptionsBuilder<ObservationDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection??throw new InvalidOperationException("No request transaction.")).Options));
|
||||
s.AddScoped<ObservationFacade>();s.AddScoped<ObservationQueries>(sp=>sp.GetRequiredService<ObservationFacade>());s.AddScoped<ObservationCommands>(sp=>sp.GetRequiredService<ObservationFacade>());return s;
|
||||
}
|
||||
public static IServiceCollection AddObservations(this IServiceCollection s)
|
||||
{
|
||||
s.AddScoped(sp => new ObservationDbContext(new DbContextOptionsBuilder<ObservationDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("No request transaction.")).Options));
|
||||
s.AddScoped<ObservationFacade>(); s.AddScoped<ObservationQueries>(sp => sp.GetRequiredService<ObservationFacade>()); s.AddScoped<ObservationCommands>(sp => sp.GetRequiredService<ObservationFacade>()); return s;
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,24 @@ using System.ComponentModel.DataAnnotations;
|
||||
using HealthApp.Contracts;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
namespace HealthApp.Overview;
|
||||
internal sealed class OverviewFacade(ProfileQueries patients,ObservationQueries observations,AnalyticsQueries analytics) : OverviewQueries
|
||||
|
||||
internal sealed class OverviewFacade(ProfileQueries patients, ObservationQueries observations, AnalyticsQueries analytics) : OverviewQueries
|
||||
{
|
||||
public async Task<HealthOverviewDto?> GetAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
from=MeasurementPeriod.Normalize(from);to=MeasurementPeriod.Normalize(to);MeasurementPeriod.Validate(from,to);Validator.ValidateObject(selection,new ValidationContext(selection),true);
|
||||
var patient=await patients.GetAsync(scope,ct);if(patient is null)return null;
|
||||
var latest=await observations.LatestAsync(scope,ct);
|
||||
// Analytics captures the selected series once and closes the shared snapshot before calculation.
|
||||
var insight=await analytics.InsightAsync(scope,from,to,selection,ct);
|
||||
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);
|
||||
}
|
||||
public async Task<HealthOverviewDto?> GetAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
from = MeasurementPeriod.Normalize(from); to = MeasurementPeriod.Normalize(to); MeasurementPeriod.Validate(from, to); Validator.ValidateObject(selection, new ValidationContext(selection), true);
|
||||
var patient = await patients.GetAsync(scope, ct); if (patient is null) return null;
|
||||
var latest = await observations.LatestAsync(scope, ct);
|
||||
// Analytics captures the selected series once and closes the shared snapshot before calculation.
|
||||
var insight = await analytics.InsightAsync(scope, from, to, selection, ct);
|
||||
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);
|
||||
}
|
||||
}
|
||||
public static class OverviewModule
|
||||
{
|
||||
public static IServiceCollection AddOverview(this IServiceCollection services)=>services.AddScoped<OverviewQueries,OverviewFacade>();
|
||||
public static IServiceCollection AddOverview(this IServiceCollection services) => services.AddScoped<OverviewQueries, OverviewFacade>();
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
[assembly: InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -7,34 +7,35 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Npgsql;
|
||||
namespace HealthApp.Profile;
|
||||
internal sealed class ProfileFacade(PatientDbContext db,RequestTransaction tx) : ProfileQueries,ProfileCommands
|
||||
|
||||
internal sealed class ProfileFacade(PatientDbContext db, RequestTransaction tx) : ProfileQueries, ProfileCommands
|
||||
{
|
||||
public async Task<Guid?> ResolveAccountAsync(string id,CancellationToken ct)
|
||||
{await tx.EnlistAsync(db,ct);return await db.Patients.AsNoTracking().Where(p=>p.AccountId==id).Select(p=>(Guid?)p.PatientId).SingleOrDefaultAsync(ct);}
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope,CancellationToken ct)
|
||||
{await tx.EnlistAsync(db,ct);var p=await db.Patients.AsNoTracking().SingleOrDefaultAsync(p=>p.PatientId==scope.PatientId,ct);return p is null?null:Dto(p);}
|
||||
public async Task<PatientDto> CreateAsync(string trustedAccountId,CreatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(trustedAccountId);Validator.ValidateObject(r,new ValidationContext(r),true);
|
||||
await tx.EnlistAsync(db,ct);if(await db.Patients.AnyAsync(p=>p.AccountId==trustedAccountId,ct))throw new ProfileAlreadyExistsException();
|
||||
var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
var p=new Patient{PatientId=Guid.NewGuid(),AccountId=trustedAccountId,Name=r.Name!,DateOfBirth=r.DateOfBirth!.Value,ContactInfo=r.ContactInfo,CreatedAt=now,UpdatedAt=now};db.Patients.Add(p);
|
||||
try{await db.SaveChangesAsync(ct);}catch(DbUpdateException e) when(e.InnerException is PostgresException {SqlState:"23505",ConstraintName:"IX_patient_account_id"}){throw new ProfileAlreadyExistsException();}
|
||||
return Dto(p);
|
||||
}
|
||||
public async Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite();Validator.ValidateObject(r,new ValidationContext(r),true);await tx.EnlistAsync(db,ct);
|
||||
var p=await db.Patients.FromSqlInterpolated($"SELECT * FROM profile.patient WHERE patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(ct);
|
||||
if(p is null)return null;p.Name=r.Name!;p.ContactInfo=r.ContactInfo;p.UpdatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);await db.SaveChangesAsync(ct);return Dto(p);
|
||||
}
|
||||
private static PatientDto Dto(Patient p)=>new(p.PatientId,p.Name,p.DateOfBirth,p.ContactInfo);
|
||||
public async Task<Guid?> ResolveAccountAsync(string id, CancellationToken ct)
|
||||
{ await tx.EnlistAsync(db, ct); return await db.Patients.AsNoTracking().Where(p => p.AccountId == id).Select(p => (Guid?)p.PatientId).SingleOrDefaultAsync(ct); }
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope, CancellationToken ct)
|
||||
{ await tx.EnlistAsync(db, ct); var p = await db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == scope.PatientId, ct); return p is null ? null : Dto(p); }
|
||||
public async Task<PatientDto> CreateAsync(string trustedAccountId, CreatePatientRequest r, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(trustedAccountId); Validator.ValidateObject(r, new ValidationContext(r), true);
|
||||
await tx.EnlistAsync(db, ct); if (await db.Patients.AnyAsync(p => p.AccountId == trustedAccountId, ct)) throw new ProfileAlreadyExistsException();
|
||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
var p = new Patient { PatientId = Guid.NewGuid(), AccountId = trustedAccountId, Name = r.Name!, DateOfBirth = r.DateOfBirth!.Value, ContactInfo = r.ContactInfo, CreatedAt = now, UpdatedAt = now }; db.Patients.Add(p);
|
||||
try { await db.SaveChangesAsync(ct); } catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: "23505", ConstraintName: "IX_patient_account_id" }) { throw new ProfileAlreadyExistsException(); }
|
||||
return Dto(p);
|
||||
}
|
||||
public async Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope, UpdatePatientRequest r, CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite(); Validator.ValidateObject(r, new ValidationContext(r), true); await tx.EnlistAsync(db, ct);
|
||||
var p = await db.Patients.FromSqlInterpolated($"SELECT * FROM profile.patient WHERE patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(ct);
|
||||
if (p is null) return null; p.Name = r.Name!; p.ContactInfo = r.ContactInfo; p.UpdatedAt = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified); await db.SaveChangesAsync(ct); return Dto(p);
|
||||
}
|
||||
private static PatientDto Dto(Patient p) => new(p.PatientId, p.Name, p.DateOfBirth, p.ContactInfo);
|
||||
}
|
||||
public static class ProfileModule
|
||||
{
|
||||
public static IServiceCollection AddProfile(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped(sp=>new PatientDbContext(new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
|
||||
services.AddScoped<ProfileFacade>();services.AddScoped<ProfileQueries>(sp=>sp.GetRequiredService<ProfileFacade>());services.AddScoped<ProfileCommands>(sp=>sp.GetRequiredService<ProfileFacade>());return services;
|
||||
}
|
||||
public static IServiceCollection AddProfile(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped(sp => new PatientDbContext(new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
|
||||
services.AddScoped<ProfileFacade>(); services.AddScoped<ProfileQueries>(sp => sp.GetRequiredService<ProfileFacade>()); services.AddScoped<ProfileCommands>(sp => sp.GetRequiredService<ProfileFacade>()); return services;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user