Implement US-01 patient profile creation and retrieval

This commit is contained in:
Steffen committed 2026-09-30 22:34:44 +02:00
1 parent d6f79a91c0
commit eb2cf2e54a
30 files changed
+792

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>
@@ -0,0 +1,58 @@
using Microsoft.AspNetCore.Mvc;
namespace ApiGateway.Controllers;
[ApiController]
[Route("api/patients")]
public sealed class PatientController(IHttpClientFactory clients) : ControllerBase
{
[HttpPost]
public Task CreatePatient(CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken);
[HttpGet("{patientId:guid}")]
public Task GetPatient(Guid patientId, CancellationToken cancellationToken) =>
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken);
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(method, path);
if (method == HttpMethod.Post)
{
request.Content = new StreamContent(Request.Body);
if (Request.ContentType is not null)
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
}
try
{
using var upstream = await clients.CreateClient("PatientProfile")
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Response.StatusCode = (int)upstream.StatusCode;
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
if (upstream.Headers.Location is { } location)
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
}
catch (HttpRequestException)
{
await WriteFailureAsync(StatusCodes.Status502BadGateway);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
}
}
private Task WriteFailureAsync(int status)
{
if (Response.HasStarted)
{
HttpContext.Abort();
return Task.CompletedTask;
}
Response.Clear();
return Results.Problem(statusCode: status, title: "Patient/Profile service is unavailable.")
.ExecuteAsync(HttpContext);
}
}
+31
View File
@@ -0,0 +1,31 @@
namespace ApiGateway;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddHttpClient("PatientProfile", (services, client) =>
client.BaseAddress = GetBaseUri(services.GetRequiredService<IConfiguration>()))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
var app = builder.Build();
_ = GetBaseUri(app.Configuration);
app.UseExceptionHandler();
app.MapControllers();
app.Run();
}
private static Uri GetBaseUri(IConfiguration configuration)
{
var endpoint = configuration["Services:PatientProfile: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.");
return baseUri;
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
@@ -0,0 +1,29 @@
using PatientProfileService.Contracts;
using PatientProfileService.Domain;
namespace PatientProfileService.Application;
public sealed class PatientApplicationService(PatientRepository repository)
{
public Task<Patient> CreatePatientAsync(CreatePatientRequest request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
if (request.DateOfBirth is null)
throw new ArgumentException("A date of birth is required.", nameof(request));
// The documented TIMESTAMP columns store UTC without a time-zone component.
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
return repository.SaveAsync(new Patient
{
PatientId = Guid.NewGuid(),
Name = request.Name,
DateOfBirth = request.DateOfBirth.Value,
ContactInfo = request.ContactInfo,
CreatedAt = now,
UpdatedAt = now
}, cancellationToken);
}
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindByIdAsync(patientId, cancellationToken);
}
@@ -0,0 +1,9 @@
using PatientProfileService.Domain;
namespace PatientProfileService.Application;
public interface PatientRepository
{
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
}
@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
namespace PatientProfileService.Contracts;
public sealed record CreatePatientRequest
{
[Required]
public string? Name { get; init; }
[Required]
public DateOnly? DateOfBirth { get; init; }
public string? ContactInfo { get; init; }
}
@@ -0,0 +1,3 @@
namespace PatientProfileService.Contracts;
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc;
using PatientProfileService.Application;
using PatientProfileService.Contracts;
using PatientProfileService.Domain;
namespace PatientProfileService.Controllers;
[ApiController]
[Route("api/patients")]
public sealed class PatientController(PatientApplicationService service) : ControllerBase
{
[HttpPost]
public async Task<ActionResult<PatientDto>> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken)
{
var patient = await service.CreatePatientAsync(request, cancellationToken);
return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient));
}
[HttpGet("{patientId:guid}")]
public async Task<ActionResult<PatientDto>> GetPatient(Guid patientId, CancellationToken cancellationToken)
{
var patient = await service.GetPatientAsync(patientId, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
private static PatientDto ToDto(Patient patient) =>
new(patient.PatientId, patient.Name, patient.DateOfBirth, patient.ContactInfo);
}
@@ -0,0 +1,11 @@
namespace PatientProfileService.Domain;
public sealed class Patient
{
public Guid PatientId { get; set; }
public string Name { get; set; } = "";
public DateOnly DateOfBirth { get; set; }
public string? ContactInfo { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,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>
@@ -0,0 +1,62 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PatientProfileService.Persistence;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
[DbContext(typeof(PatientDbContext))]
[Migration("20260930200031_InitialPatientSchema")]
partial class InitialPatientSchema
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("PatientProfileService.Domain.Patient", b =>
{
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("ContactInfo")
.HasColumnType("character varying")
.HasColumnName("contact_info");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<DateOnly>("DateOfBirth")
.HasColumnType("date")
.HasColumnName("date_of_birth");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("character varying")
.HasColumnName("name");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("PatientId");
b.ToTable("patient", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
/// <inheritdoc />
public partial class InitialPatientSchema : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "patient",
columns: table => new
{
patient_id = table.Column<Guid>(type: "uuid", nullable: false),
name = table.Column<string>(type: "character varying", nullable: false),
date_of_birth = table.Column<DateOnly>(type: "date", nullable: false),
contact_info = table.Column<string>(type: "character varying", nullable: true),
created_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
updated_at = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_patient", x => x.patient_id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "patient");
}
}
}
@@ -0,0 +1,59 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PatientProfileService.Persistence;
#nullable disable
namespace PatientProfileService.Persistence.Migrations
{
[DbContext(typeof(PatientDbContext))]
partial class PatientDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("PatientProfileService.Domain.Patient", b =>
{
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("ContactInfo")
.HasColumnType("character varying")
.HasColumnName("contact_info");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("created_at");
b.Property<DateOnly>("DateOfBirth")
.HasColumnType("date")
.HasColumnName("date_of_birth");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("character varying")
.HasColumnName("name");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp without time zone")
.HasColumnName("updated_at");
b.HasKey("PatientId");
b.ToTable("patient", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore;
using PatientProfileService.Domain;
namespace PatientProfileService.Persistence;
public sealed class PatientDbContext(DbContextOptions<PatientDbContext> options) : DbContext(options)
{
public DbSet<Patient> Patients => Set<Patient>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var patient = modelBuilder.Entity<Patient>();
patient.ToTable("patient");
patient.HasKey(p => p.PatientId);
patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired();
patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date");
patient.Property(p => p.ContactInfo).HasColumnName("contact_info").HasColumnType("character varying");
patient.Property(p => p.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
patient.Property(p => p.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
}
}
@@ -0,0 +1,18 @@
using Microsoft.EntityFrameworkCore;
using PatientProfileService.Application;
using PatientProfileService.Domain;
namespace PatientProfileService.Persistence;
public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepository
{
public async Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken)
{
db.Patients.Add(patient);
await db.SaveChangesAsync(cancellationToken);
return patient;
}
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
}
+34
View File
@@ -0,0 +1,34 @@
using Microsoft.EntityFrameworkCore;
using PatientProfileService.Application;
using PatientProfileService.Persistence;
namespace PatientProfileService;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddDbContext<PatientDbContext>((services, options) =>
options.UseNpgsql(services.GetRequiredService<IConfiguration>().GetConnectionString("PatientDatabase")));
builder.Services.AddScoped<PatientRepository, SqlPatientRepository>();
builder.Services.AddScoped<PatientApplicationService>();
var app = builder.Build();
if (string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("PatientDatabase")))
throw new InvalidOperationException("ConnectionStrings:PatientDatabase must be configured.");
if (args.Contains("--migrate"))
{
await using var scope = app.Services.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<PatientDbContext>().Database.MigrateAsync();
return;
}
app.UseExceptionHandler();
app.MapControllers();
await app.RunAsync();
}
}
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
}
}
+72
View File
@@ -0,0 +1,72 @@
# US-01: Create a patient profile
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 are implemented.
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. Update-profile functionality belongs to a later story.
## Build and run
Install a .NET 10 SDK and provision an empty PostgreSQL database owned by the Patient/Profile service's database user. From the repository root:
```bash
dotnet restore HealthApp.slnx
dotnet build HealthApp.slnx -c Release --no-restore
# In the Patient/Profile service terminal; substitute your own database configuration.
export ConnectionStrings__PatientDatabase='Host=127.0.0.1;Database=patient_profile;Username=patient_profile;Password=YOUR_LOCAL_PASSWORD'
dotnet run --project src/PatientProfileService -c Release --no-build -- --migrate
ASPNETCORE_URLS=http://127.0.0.1:5081 dotnet run --project src/PatientProfileService -c Release --no-build
# In a separate gateway terminal.
Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build
```
`--migrate` applies committed EF Core migrations and exits. Apply migrations as a deployment step before starting the service; normal startup does not modify the schema. Both services fail startup with a clear message if required configuration is absent. Configuration uses standard .NET JSON files, environment variables, and command-line arguments. Service endpoints and database hosts may be remote.
## API
Send requests to the gateway:
```bash
curl -i http://127.0.0.1:5080/api/patients \
-H 'Content-Type: application/json' \
-d '{"name":"Steffen Example","dateOfBirth":"1980-01-01","contactInfo":"steffen@example.test"}'
```
`POST /api/patients` returns `201 Created`, a relative `Location: /api/patients/{patientId}` header, and a JSON profile containing `patientId`, `name`, `dateOfBirth`, and `contactInfo`. Identifiers are generated UUIDs and the database primary key enforces uniqueness. Names must be nonblank; dates of birth must be supplied as valid `YYYY-MM-DD` dates. Invalid requests return `400` validation problem details and do not create profiles. Contact information is optional because US-01 does not require it.
`GET /api/patients/{patientId}` retrieves the persisted profile, or returns `404` when absent. Retrieval is included because US-01 explicitly requires it. The gateway returns `502` for connection failures and `504` for upstream timeouts.
Authentication and authorization policy is unspecified; the gap is recorded in `suggestions/api-gateway-authentication.md`. No access policy has been invented for US-01.
## Automated acceptance tests
Tests require a real PostgreSQL instance. Provide an administrator connection with permission to create/drop databases; the fixture creates an isolated database named `us01_<random>`, applies the committed migration, and deletes that database at teardown. Never point this connection at a production server.
```bash
TEST_POSTGRES_CONNECTION='Host=127.0.0.1;Database=postgres;Username=postgres;Password=YOUR_LOCAL_TEST_PASSWORD' \
dotnet test HealthApp.slnx -c Release
```
The xUnit tests send HTTP requests to the gateway; the gateway reaches a real Kestrel Patient/Profile service over HTTP. They cover every US-01 acceptance scenario, retrieval after host restart, distinct identifiers, optional contact information, invalid JSON/dates, and rejection without database writes. Test assertions use an independent HTTP response contract. Production projects have no references to each other's implementation.
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
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
```
Copy each output to its corresponding `/opt/healthapp/` directory on the intended host, install the ASP.NET Core 10 runtime, and create a `healthapp` service user/group. Adjust the paths/user in `deploy/systemd/*.service` for the host. Copy the environment examples to `/etc/healthapp/patient-profile.env` and `/etc/healthapp/api-gateway.env`, replace example values, and restrict their permissions to protect credentials. Configure the gateway certificate for the HTTPS client entry point. Its example uses a PFX certificate; standard Kestrel configuration also supports other certificate formats.
Apply the database migration using the published Patient/Profile executable with its database configuration:
```bash
dotnet /opt/healthapp/patient-profile/PatientProfileService.dll --migrate
```
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.