Implement US-04 blood-pressure observation recording
This commit is contained in:
1 parent
a9633e49e1
commit
05f57dcba3
25 files changed
+843
-9
No files matched your search
@@ -0,0 +1,58 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ApiGateway.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class ObservationController(IHttpClientFactory clients) : ControllerBase
|
||||
{
|
||||
[HttpPost("patients/{patientId:guid}/observations")]
|
||||
public Task RecordObservation(Guid patientId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Post, $"api/patients/{patientId}/observations", cancellationToken);
|
||||
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public Task GetObservation(Guid observationId, CancellationToken cancellationToken) =>
|
||||
ForwardAsync(HttpMethod.Get, $"api/observations/{observationId}", cancellationToken);
|
||||
|
||||
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
if (method == HttpMethod.Post)
|
||||
{
|
||||
request.Content = new StreamContent(Request.Body);
|
||||
if (Request.ContentType is not null)
|
||||
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var upstream = await clients.CreateClient("Observation")
|
||||
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
Response.StatusCode = (int)upstream.StatusCode;
|
||||
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
|
||||
if (upstream.Headers.Location is { } location)
|
||||
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
|
||||
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
await WriteFailureAsync(StatusCodes.Status502BadGateway);
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
private Task WriteFailureAsync(int status)
|
||||
{
|
||||
if (Response.HasStarted)
|
||||
{
|
||||
HttpContext.Abort();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
Response.Clear();
|
||||
return Results.Problem(statusCode: status, title: "Observation service is unavailable.")
|
||||
.ExecuteAsync(HttpContext);
|
||||
}
|
||||
}
|
||||
@@ -8,24 +8,29 @@ public class Program
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddHttpClient("PatientProfile", (services, client) =>
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>()))
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "PatientProfile"))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
builder.Services.AddHttpClient("Observation", (services, client) =>
|
||||
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>(), "Observation"))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
var app = builder.Build();
|
||||
_ = GetBaseUri(app.Configuration);
|
||||
_ = GetBaseUri(app.Configuration, "PatientProfile");
|
||||
_ = GetBaseUri(app.Configuration, "Observation");
|
||||
app.UseExceptionHandler();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
}
|
||||
|
||||
private static Uri GetBaseUri(IConfiguration configuration)
|
||||
private static Uri GetBaseUri(IConfiguration configuration, string service)
|
||||
{
|
||||
var endpoint = configuration["Services:PatientProfile:BaseUrl"];
|
||||
var endpoint = configuration[$"Services:{service}:BaseUrl"];
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var baseUri) ||
|
||||
(baseUri.Scheme != "http" && baseUri.Scheme != "https") ||
|
||||
baseUri.AbsolutePath != "/" || !string.IsNullOrEmpty(baseUri.Query) ||
|
||||
!string.IsNullOrEmpty(baseUri.Fragment) || !string.IsNullOrEmpty(baseUri.UserInfo))
|
||||
throw new InvalidOperationException("Services:PatientProfile:BaseUrl must be an HTTP(S) origin URL.");
|
||||
throw new InvalidOperationException($"Services:{service}:BaseUrl must be an HTTP(S) origin URL.");
|
||||
return baseUri;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Net;
|
||||
using ObservationService.Contracts;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Application;
|
||||
|
||||
public sealed class ObservationApplicationService(ObservationRepository repository, IHttpClientFactory clients)
|
||||
{
|
||||
public async Task<BloodPressureObservation?> RecordAsync(Guid patientId, RecordObservationRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.MeasuredAt is null || request.Systolic is null or <= 0 ||
|
||||
request.Diastolic is null or <= 0 || request.Pulse is null or <= 0)
|
||||
throw new ArgumentException("A timestamp and positive measured values are required.", nameof(request));
|
||||
|
||||
using var patient = await clients.CreateClient("ApiGateway").GetAsync($"api/patients/{patientId}",
|
||||
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
if (patient.StatusCode == HttpStatusCode.NotFound)
|
||||
return null;
|
||||
// Upstream failures must never be interpreted as an existing patient.
|
||||
patient.EnsureSuccessStatusCode();
|
||||
|
||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
var measuredAt = request.MeasuredAt.Value;
|
||||
if (measuredAt.Kind != DateTimeKind.Unspecified)
|
||||
measuredAt = measuredAt.ToUniversalTime();
|
||||
|
||||
return await repository.SaveAsync(new BloodPressureObservation
|
||||
{
|
||||
ObservationId = Guid.NewGuid(), PatientId = patientId,
|
||||
MeasuredAt = DateTime.SpecifyKind(measuredAt, DateTimeKind.Unspecified),
|
||||
Systolic = request.Systolic.Value, Diastolic = request.Diastolic.Value,
|
||||
Pulse = request.Pulse.Value, Context = request.Context, Note = request.Note,
|
||||
CreatedAt = now, UpdatedAt = now
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<BloodPressureObservation?> GetByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
|
||||
repository.FindByIdAsync(observationId, cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Application;
|
||||
|
||||
public interface ObservationRepository
|
||||
{
|
||||
Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken);
|
||||
Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace ObservationService.Contracts;
|
||||
|
||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace ObservationService.Contracts;
|
||||
|
||||
public sealed record RecordObservationRequest
|
||||
{
|
||||
[Required]
|
||||
public DateTime? MeasuredAt { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Systolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Diastolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Pulse { get; init; }
|
||||
|
||||
public string? Context { get; init; }
|
||||
public string? Note { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ObservationService.Application;
|
||||
using ObservationService.Contracts;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api")]
|
||||
public sealed class ObservationController(ObservationApplicationService service) : ControllerBase
|
||||
{
|
||||
[HttpPost("patients/{patientId:guid}/observations")]
|
||||
public async Task<ActionResult<ObservationDto>> RecordObservation(Guid patientId, RecordObservationRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var observation = await service.RecordAsync(patientId, request, cancellationToken);
|
||||
return observation is null
|
||||
? NotFound()
|
||||
: CreatedAtAction(nameof(GetObservation), new { observationId = observation.ObservationId }, ToDto(observation));
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status502BadGateway, title: "Patient lookup is unavailable.");
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return Problem(statusCode: StatusCodes.Status504GatewayTimeout, title: "Patient lookup timed out.");
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public async Task<ActionResult<ObservationDto>> GetObservation(Guid observationId, CancellationToken cancellationToken)
|
||||
{
|
||||
var observation = await service.GetByIdAsync(observationId, cancellationToken);
|
||||
return observation is null ? NotFound() : Ok(ToDto(observation));
|
||||
}
|
||||
|
||||
private static ObservationDto ToDto(BloodPressureObservation observation) =>
|
||||
new(observation.ObservationId, observation.PatientId, observation.MeasuredAt, observation.Systolic,
|
||||
observation.Diastolic, observation.Pulse, observation.Context, observation.Note);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace ObservationService.Domain;
|
||||
|
||||
public sealed class BloodPressureObservation
|
||||
{
|
||||
public Guid ObservationId { get; set; }
|
||||
public Guid PatientId { get; set; }
|
||||
public DateTime MeasuredAt { get; set; }
|
||||
public int Systolic { get; set; }
|
||||
public int Diastolic { get; set; }
|
||||
public int Pulse { get; set; }
|
||||
public string? Context { get; set; }
|
||||
public string? Note { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Generated
+77
@@ -0,0 +1,77 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using ObservationService.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ObservationService.Persistence.Migrations
|
||||
{
|
||||
[DbContext(typeof(ObservationDbContext))]
|
||||
[Migration("20261001095222_InitialObservationSchema")]
|
||||
partial class InitialObservationSchema
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
|
||||
{
|
||||
b.Property<Guid>("ObservationId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("observation_id");
|
||||
|
||||
b.Property<string>("Context")
|
||||
.HasColumnType("character varying")
|
||||
.HasColumnName("context");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp without time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<int>("Diastolic")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("diastolic");
|
||||
|
||||
b.Property<DateTime>("MeasuredAt")
|
||||
.HasColumnType("timestamp without time zone")
|
||||
.HasColumnName("measured_at");
|
||||
|
||||
b.Property<string>("Note")
|
||||
.HasColumnType("character varying")
|
||||
.HasColumnName("note");
|
||||
|
||||
b.Property<Guid>("PatientId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("patient_id");
|
||||
|
||||
b.Property<int>("Pulse")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("pulse");
|
||||
|
||||
b.Property<int>("Systolic")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("systolic");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp without time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.HasKey("ObservationId");
|
||||
|
||||
b.ToTable("blood_pressure_observation", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ObservationService.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialObservationSchema : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "blood_pressure_observation",
|
||||
columns: table => new
|
||||
{
|
||||
observation_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
patient_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
measured_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
systolic = table.Column<int>(type: "integer", nullable: false),
|
||||
diastolic = table.Column<int>(type: "integer", nullable: false),
|
||||
pulse = table.Column<int>(type: "integer", nullable: false),
|
||||
context = table.Column<string>(type: "character varying", nullable: true),
|
||||
note = table.Column<string>(type: "character varying", nullable: true),
|
||||
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
|
||||
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_blood_pressure_observation", x => x.observation_id);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "blood_pressure_observation");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using ObservationService.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ObservationService.Persistence.Migrations
|
||||
{
|
||||
[DbContext(typeof(ObservationDbContext))]
|
||||
partial class ObservationDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("ObservationService.Domain.BloodPressureObservation", b =>
|
||||
{
|
||||
b.Property<Guid>("ObservationId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("observation_id");
|
||||
|
||||
b.Property<string>("Context")
|
||||
.HasColumnType("character varying")
|
||||
.HasColumnName("context");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp without time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<int>("Diastolic")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("diastolic");
|
||||
|
||||
b.Property<DateTime>("MeasuredAt")
|
||||
.HasColumnType("timestamp without time zone")
|
||||
.HasColumnName("measured_at");
|
||||
|
||||
b.Property<string>("Note")
|
||||
.HasColumnType("character varying")
|
||||
.HasColumnName("note");
|
||||
|
||||
b.Property<Guid>("PatientId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("patient_id");
|
||||
|
||||
b.Property<int>("Pulse")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("pulse");
|
||||
|
||||
b.Property<int>("Systolic")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("systolic");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp without time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.HasKey("ObservationId");
|
||||
|
||||
b.ToTable("blood_pressure_observation", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Persistence;
|
||||
|
||||
public sealed class ObservationDbContext(DbContextOptions<ObservationDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<BloodPressureObservation> Observations => Set<BloodPressureObservation>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var observation = modelBuilder.Entity<BloodPressureObservation>();
|
||||
observation.ToTable("blood_pressure_observation");
|
||||
observation.HasKey(o => o.ObservationId);
|
||||
observation.Property(o => o.ObservationId).HasColumnName("observation_id").ValueGeneratedNever();
|
||||
// An external patient identifier, not a cross-database foreign key.
|
||||
observation.Property(o => o.PatientId).HasColumnName("patient_id");
|
||||
observation.Property(o => o.MeasuredAt).HasColumnName("measured_at").HasColumnType("timestamp without time zone");
|
||||
observation.Property(o => o.Systolic).HasColumnName("systolic");
|
||||
observation.Property(o => o.Diastolic).HasColumnName("diastolic");
|
||||
observation.Property(o => o.Pulse).HasColumnName("pulse");
|
||||
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
|
||||
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
|
||||
observation.Property(o => o.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
|
||||
observation.Property(o => o.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ObservationService.Application;
|
||||
using ObservationService.Domain;
|
||||
|
||||
namespace ObservationService.Persistence;
|
||||
|
||||
public sealed class SqlObservationRepository(ObservationDbContext db) : ObservationRepository
|
||||
{
|
||||
public async Task<BloodPressureObservation> SaveAsync(BloodPressureObservation observation, CancellationToken cancellationToken)
|
||||
{
|
||||
db.Observations.Add(observation);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return observation;
|
||||
}
|
||||
|
||||
public Task<BloodPressureObservation?> FindByIdAsync(Guid observationId, CancellationToken cancellationToken) =>
|
||||
db.Observations.AsNoTracking().SingleOrDefaultAsync(o => o.ObservationId == observationId, cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ObservationService.Application;
|
||||
using ObservationService.Persistence;
|
||||
|
||||
namespace ObservationService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddDbContext<ObservationDbContext>((services, options) =>
|
||||
options.UseNpgsql(services.GetRequiredService<IConfiguration>().GetConnectionString("ObservationDatabase")));
|
||||
builder.Services.AddScoped<ObservationRepository, SqlObservationRepository>();
|
||||
builder.Services.AddScoped<ObservationApplicationService>();
|
||||
builder.Services.AddHttpClient("ApiGateway", (services, client) =>
|
||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
|
||||
var app = builder.Build();
|
||||
if (string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("ObservationDatabase")))
|
||||
throw new InvalidOperationException("ConnectionStrings:ObservationDatabase must be configured.");
|
||||
|
||||
if (args.Contains("--migrate"))
|
||||
{
|
||||
await using var scope = app.Services.CreateAsyncScope();
|
||||
await scope.ServiceProvider.GetRequiredService<ObservationDbContext>().Database.MigrateAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
_ = GetGatewayUri(app.Configuration);
|
||||
app.UseExceptionHandler();
|
||||
app.MapControllers();
|
||||
await app.RunAsync();
|
||||
}
|
||||
|
||||
private static Uri GetGatewayUri(IConfiguration configuration)
|
||||
{
|
||||
var endpoint = configuration["Services:ApiGateway:BaseUrl"];
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
|
||||
(uri.Scheme != "http" && uri.Scheme != "https") || uri.AbsolutePath != "/" ||
|
||||
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) || !string.IsNullOrEmpty(uri.UserInfo))
|
||||
throw new InvalidOperationException("Services:ApiGateway:BaseUrl must be an HTTP(S) origin URL.");
|
||||
return uri;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-3
@@ -1,6 +1,6 @@
|
||||
# US-01–US-03: Create, view and update a patient profile
|
||||
# US-01–US-04: Patient profiles and blood-pressure recording
|
||||
|
||||
Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway and Patient/Profile service are separate executables and can run on separate machines. Only the services needed for US-01–US-03 are implemented.
|
||||
Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway, Patient/Profile service and Observation Service are separate executables and can run on separate machines. Each domain service owns its database.
|
||||
|
||||
The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns.
|
||||
|
||||
@@ -18,7 +18,12 @@ dotnet run --project src/PatientProfileService -c Release --no-build -- --migrat
|
||||
ASPNETCORE_URLS=http://127.0.0.1:5081 dotnet run --project src/PatientProfileService -c Release --no-build
|
||||
|
||||
# In a separate gateway terminal.
|
||||
Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build
|
||||
Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ Services__Observation__BaseUrl=http://127.0.0.1:5082/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build
|
||||
|
||||
# In a separate observation terminal, with its own provisioned database.
|
||||
export ConnectionStrings__ObservationDatabase='Host=127.0.0.1;Database=observations;Username=observations;Password=YOUR_LOCAL_PASSWORD'
|
||||
dotnet run --project src/ObservationService -c Release --no-build -- --migrate
|
||||
Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5082 dotnet run --project src/ObservationService -c Release --no-build
|
||||
```
|
||||
|
||||
`--migrate` applies committed EF Core migrations and exits. Apply migrations as a deployment step before starting the service; normal startup does not modify the schema. Both services fail startup with a clear message if required configuration is absent. Configuration uses standard .NET JSON files, environment variables, and command-line arguments. Service endpoints and database hosts may be remote.
|
||||
@@ -39,6 +44,10 @@ curl -i http://127.0.0.1:5080/api/patients \
|
||||
|
||||
`PUT /api/patients/{patientId}` updates the name and contact information and returns `200` with the updated profile. It preserves the patient identifier, date of birth and creation timestamp, and updates the modification timestamp. Names must be nonblank, consistent with profile creation; omitted or null contact information clears that optional value. A missing patient returns `404` without creating a profile. Invalid requests return `400` without changing stored information.
|
||||
|
||||
`POST /api/patients/{patientId}/observations` records a blood-pressure observation. Supply `measuredAt`, positive integer `systolic`, `diastolic` and `pulse`, plus optional `context` and `note`. It returns `201`, the saved observation including its generated `observationId` and `patientId`, and `Location: /api/observations/{observationId}`. `GET` at that location retrieves the persisted observation, or returns `404` if absent. Retrieval is included to satisfy US-04's requirement that a recorded observation can be retrieved later.
|
||||
|
||||
The Observation Service checks patient existence by calling the gateway's patient retrieval API over HTTP before saving. It has no reference to Patient/Profile implementation code and no access to that service's database. Missing patients return `404`; validation failures return `400`. Patient lookup failures return `502` or `504` and do not save an observation. Measurement timestamps without an offset are stored as supplied; timestamps with an offset are normalized to UTC. PostgreSQL uses the diagram's `timestamp` columns without a time-zone component.
|
||||
|
||||
Authentication and access control are defined in US-13, US-14 and `Docs/Design/authentication-and-access-control-design.md`, and remain to be implemented as separate stories. These endpoints currently have no access restrictions.
|
||||
|
||||
## Automated acceptance tests
|
||||
@@ -54,6 +63,8 @@ The xUnit tests send HTTP requests to the gateway; the gateway reaches a real Ke
|
||||
|
||||
US-02 retrieval scenarios are covered by the creation tests. US-03 tests cover persisted updates after restart, preservation of identity and date of birth, missing-patient rejection without insertion, and invalid-name rejection without changing the profile.
|
||||
|
||||
US-04 tests use real HTTP between all three hosts and separate temporary patient and observation databases. They cover every recording acceptance scenario, retrieval after restart, optional fields, distinct identifiers, malformed/missing fields, missing observations, and patient-lookup failure without database writes. Both services' committed migrations are applied twice to verify idempotence. The Observation Service uses the same EF Core PostgreSQL dependencies as Patient/Profile for its independent persistence; no new library types are introduced.
|
||||
|
||||
Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency.
|
||||
|
||||
## Linux deployment
|
||||
@@ -63,6 +74,7 @@ Publish each service separately:
|
||||
```bash
|
||||
dotnet publish src/PatientProfileService -c Release -o /tmp/healthapp-publish/patient-profile
|
||||
dotnet publish src/ApiGateway -c Release -o /tmp/healthapp-publish/api-gateway
|
||||
dotnet publish src/ObservationService -c Release -o /tmp/healthapp-publish/observation
|
||||
```
|
||||
|
||||
Copy each output to its corresponding `/opt/healthapp/` directory on the intended host, install the ASP.NET Core 10 runtime, and create a `healthapp` service user/group. Adjust the paths/user in `deploy/systemd/*.service` for the host. Copy the environment examples to `/etc/healthapp/patient-profile.env` and `/etc/healthapp/api-gateway.env`, replace example values, and restrict their permissions to protect credentials. Configure the gateway certificate for the HTTPS client entry point. Its example uses a PFX certificate; standard Kestrel configuration also supports other certificate formats.
|
||||
@@ -71,6 +83,9 @@ Apply the database migration using the published Patient/Profile executable with
|
||||
|
||||
```bash
|
||||
dotnet /opt/healthapp/patient-profile/PatientProfileService.dll --migrate
|
||||
dotnet /opt/healthapp/observation/ObservationService.dll --migrate
|
||||
```
|
||||
|
||||
Install the corresponding unit on each host and enable/start it with systemd. The units are independent, write logs to journald, restart after failures, and allow graceful shutdown. The gateway has no systemd dependency on a local Patient/Profile process; it uses the configured network endpoint.
|
||||
|
||||
The Observation Service has its own `healthapp-observation.service` unit and environment example. Configure its `Services__ApiGateway__BaseUrl` and the gateway's `Services__Observation__BaseUrl` for the deployed hosts. Apply its migration with its own database configuration. Services need not be started in a fixed order; requests needing an unavailable upstream fail without saving observations.
|
||||
Reference in new issue
Block a user