diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..00e42d5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+**/bin/
+**/obj/
+TestResults/
+.env
+*.user
diff --git a/HealthApp.slnx b/HealthApp.slnx
new file mode 100644
index 0000000..fddd3bb
--- /dev/null
+++ b/HealthApp.slnx
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/deploy/api-gateway.env.example b/deploy/api-gateway.env.example
new file mode 100644
index 0000000..0d1934c
--- /dev/null
+++ b/deploy/api-gateway.env.example
@@ -0,0 +1,5 @@
+ASPNETCORE_ENVIRONMENT=Production
+Services__PatientProfile__BaseUrl=http://patient-profile.example.test:5081/
+ASPNETCORE_URLS=https://0.0.0.0:5443
+Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx
+Kestrel__Certificates__Default__Password=REPLACE_ME
diff --git a/deploy/patient-profile.env.example b/deploy/patient-profile.env.example
new file mode 100644
index 0000000..d585d46
--- /dev/null
+++ b/deploy/patient-profile.env.example
@@ -0,0 +1,3 @@
+ASPNETCORE_ENVIRONMENT=Production
+ASPNETCORE_URLS=http://0.0.0.0:5081
+ConnectionStrings__PatientDatabase="Host=database.example.test;Port=5432;Database=patient_profile;Username=patient_profile;Password=REPLACE_ME"
diff --git a/deploy/systemd/healthapp-api-gateway.service b/deploy/systemd/healthapp-api-gateway.service
new file mode 100644
index 0000000..05911a3
--- /dev/null
+++ b/deploy/systemd/healthapp-api-gateway.service
@@ -0,0 +1,20 @@
+[Unit]
+Description=HealthApp API gateway
+Wants=network-online.target
+After=network-online.target
+
+[Service]
+Type=simple
+User=healthapp
+Group=healthapp
+WorkingDirectory=/opt/healthapp/api-gateway
+ExecStart=/usr/bin/dotnet /opt/healthapp/api-gateway/ApiGateway.dll
+EnvironmentFile=/etc/healthapp/api-gateway.env
+Restart=on-failure
+RestartSec=5
+KillSignal=SIGINT
+TimeoutStopSec=30
+SyslogIdentifier=healthapp-api-gateway
+
+[Install]
+WantedBy=multi-user.target
diff --git a/deploy/systemd/healthapp-patient-profile.service b/deploy/systemd/healthapp-patient-profile.service
new file mode 100644
index 0000000..c64e26f
--- /dev/null
+++ b/deploy/systemd/healthapp-patient-profile.service
@@ -0,0 +1,20 @@
+[Unit]
+Description=HealthApp Patient/Profile service
+Wants=network-online.target
+After=network-online.target
+
+[Service]
+Type=simple
+User=healthapp
+Group=healthapp
+WorkingDirectory=/opt/healthapp/patient-profile
+ExecStart=/usr/bin/dotnet /opt/healthapp/patient-profile/PatientProfileService.dll
+EnvironmentFile=/etc/healthapp/patient-profile.env
+Restart=on-failure
+RestartSec=5
+KillSignal=SIGINT
+TimeoutStopSec=30
+SyslogIdentifier=healthapp-patient-profile
+
+[Install]
+WantedBy=multi-user.target
diff --git a/global.json b/global.json
new file mode 100644
index 0000000..512142d
--- /dev/null
+++ b/global.json
@@ -0,0 +1,6 @@
+{
+ "sdk": {
+ "version": "10.0.100",
+ "rollForward": "latestFeature"
+ }
+}
diff --git a/src/ApiGateway/ApiGateway.csproj b/src/ApiGateway/ApiGateway.csproj
new file mode 100644
index 0000000..9a04a31
--- /dev/null
+++ b/src/ApiGateway/ApiGateway.csproj
@@ -0,0 +1,7 @@
+
+
+ net10.0
+ enable
+ enable
+
+
diff --git a/src/ApiGateway/Controllers/PatientController.cs b/src/ApiGateway/Controllers/PatientController.cs
new file mode 100644
index 0000000..c88b71c
--- /dev/null
+++ b/src/ApiGateway/Controllers/PatientController.cs
@@ -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);
+ }
+}
diff --git a/src/ApiGateway/Program.cs b/src/ApiGateway/Program.cs
new file mode 100644
index 0000000..ac3a231
--- /dev/null
+++ b/src/ApiGateway/Program.cs
@@ -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()))
+ .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;
+ }
+}
diff --git a/src/ApiGateway/appsettings.json b/src/ApiGateway/appsettings.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/src/ApiGateway/appsettings.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/src/PatientProfileService/Application/PatientApplicationService.cs b/src/PatientProfileService/Application/PatientApplicationService.cs
new file mode 100644
index 0000000..922d5db
--- /dev/null
+++ b/src/PatientProfileService/Application/PatientApplicationService.cs
@@ -0,0 +1,29 @@
+using PatientProfileService.Contracts;
+using PatientProfileService.Domain;
+
+namespace PatientProfileService.Application;
+
+public sealed class PatientApplicationService(PatientRepository repository)
+{
+ public Task 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 GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
+ repository.FindByIdAsync(patientId, cancellationToken);
+}
diff --git a/src/PatientProfileService/Application/PatientRepository.cs b/src/PatientProfileService/Application/PatientRepository.cs
new file mode 100644
index 0000000..8847caa
--- /dev/null
+++ b/src/PatientProfileService/Application/PatientRepository.cs
@@ -0,0 +1,9 @@
+using PatientProfileService.Domain;
+
+namespace PatientProfileService.Application;
+
+public interface PatientRepository
+{
+ Task SaveAsync(Patient patient, CancellationToken cancellationToken);
+ Task FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
+}
diff --git a/src/PatientProfileService/Contracts/CreatePatientRequest.cs b/src/PatientProfileService/Contracts/CreatePatientRequest.cs
new file mode 100644
index 0000000..b0f8a91
--- /dev/null
+++ b/src/PatientProfileService/Contracts/CreatePatientRequest.cs
@@ -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; }
+}
diff --git a/src/PatientProfileService/Contracts/PatientDto.cs b/src/PatientProfileService/Contracts/PatientDto.cs
new file mode 100644
index 0000000..b6e23a4
--- /dev/null
+++ b/src/PatientProfileService/Contracts/PatientDto.cs
@@ -0,0 +1,3 @@
+namespace PatientProfileService.Contracts;
+
+public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
diff --git a/src/PatientProfileService/Controllers/PatientController.cs b/src/PatientProfileService/Controllers/PatientController.cs
new file mode 100644
index 0000000..d03ebb0
--- /dev/null
+++ b/src/PatientProfileService/Controllers/PatientController.cs
@@ -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> 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> 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);
+}
diff --git a/src/PatientProfileService/Domain/Patient.cs b/src/PatientProfileService/Domain/Patient.cs
new file mode 100644
index 0000000..c36ace6
--- /dev/null
+++ b/src/PatientProfileService/Domain/Patient.cs
@@ -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; }
+}
diff --git a/src/PatientProfileService/PatientProfileService.csproj b/src/PatientProfileService/PatientProfileService.csproj
new file mode 100644
index 0000000..8f6187b
--- /dev/null
+++ b/src/PatientProfileService/PatientProfileService.csproj
@@ -0,0 +1,12 @@
+
+
+ net10.0
+ enable
+ enable
+
+
+
+
+
+
+
diff --git a/src/PatientProfileService/Persistence/Migrations/20260930200031_InitialPatientSchema.Designer.cs b/src/PatientProfileService/Persistence/Migrations/20260930200031_InitialPatientSchema.Designer.cs
new file mode 100644
index 0000000..0c2b0a6
--- /dev/null
+++ b/src/PatientProfileService/Persistence/Migrations/20260930200031_InitialPatientSchema.Designer.cs
@@ -0,0 +1,62 @@
+//
+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
+ {
+ ///
+ 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("PatientId")
+ .HasColumnType("uuid")
+ .HasColumnName("patient_id");
+
+ b.Property("ContactInfo")
+ .HasColumnType("character varying")
+ .HasColumnName("contact_info");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp without time zone")
+ .HasColumnName("created_at");
+
+ b.Property("DateOfBirth")
+ .HasColumnType("date")
+ .HasColumnName("date_of_birth");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("character varying")
+ .HasColumnName("name");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp without time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("PatientId");
+
+ b.ToTable("patient", (string)null);
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/PatientProfileService/Persistence/Migrations/20260930200031_InitialPatientSchema.cs b/src/PatientProfileService/Persistence/Migrations/20260930200031_InitialPatientSchema.cs
new file mode 100644
index 0000000..7921534
--- /dev/null
+++ b/src/PatientProfileService/Persistence/Migrations/20260930200031_InitialPatientSchema.cs
@@ -0,0 +1,38 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace PatientProfileService.Persistence.Migrations
+{
+ ///
+ public partial class InitialPatientSchema : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "patient",
+ columns: table => new
+ {
+ patient_id = table.Column(type: "uuid", nullable: false),
+ name = table.Column(type: "character varying", nullable: false),
+ date_of_birth = table.Column(type: "date", nullable: false),
+ contact_info = table.Column(type: "character varying", nullable: true),
+ created_at = table.Column(type: "timestamp without time zone", nullable: false),
+ updated_at = table.Column(type: "timestamp without time zone", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_patient", x => x.patient_id);
+ });
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "patient");
+ }
+ }
+}
diff --git a/src/PatientProfileService/Persistence/Migrations/PatientDbContextModelSnapshot.cs b/src/PatientProfileService/Persistence/Migrations/PatientDbContextModelSnapshot.cs
new file mode 100644
index 0000000..d8edb4d
--- /dev/null
+++ b/src/PatientProfileService/Persistence/Migrations/PatientDbContextModelSnapshot.cs
@@ -0,0 +1,59 @@
+//
+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("PatientId")
+ .HasColumnType("uuid")
+ .HasColumnName("patient_id");
+
+ b.Property("ContactInfo")
+ .HasColumnType("character varying")
+ .HasColumnName("contact_info");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp without time zone")
+ .HasColumnName("created_at");
+
+ b.Property("DateOfBirth")
+ .HasColumnType("date")
+ .HasColumnName("date_of_birth");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("character varying")
+ .HasColumnName("name");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp without time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("PatientId");
+
+ b.ToTable("patient", (string)null);
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/PatientProfileService/Persistence/PatientDbContext.cs b/src/PatientProfileService/Persistence/PatientDbContext.cs
new file mode 100644
index 0000000..794ab62
--- /dev/null
+++ b/src/PatientProfileService/Persistence/PatientDbContext.cs
@@ -0,0 +1,22 @@
+using Microsoft.EntityFrameworkCore;
+using PatientProfileService.Domain;
+
+namespace PatientProfileService.Persistence;
+
+public sealed class PatientDbContext(DbContextOptions options) : DbContext(options)
+{
+ public DbSet Patients => Set();
+
+ protected override void OnModelCreating(ModelBuilder modelBuilder)
+ {
+ var patient = modelBuilder.Entity();
+ 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");
+ }
+}
diff --git a/src/PatientProfileService/Persistence/SqlPatientRepository.cs b/src/PatientProfileService/Persistence/SqlPatientRepository.cs
new file mode 100644
index 0000000..e2ad4a8
--- /dev/null
+++ b/src/PatientProfileService/Persistence/SqlPatientRepository.cs
@@ -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 SaveAsync(Patient patient, CancellationToken cancellationToken)
+ {
+ db.Patients.Add(patient);
+ await db.SaveChangesAsync(cancellationToken);
+ return patient;
+ }
+
+ public Task FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
+ db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
+}
diff --git a/src/PatientProfileService/Program.cs b/src/PatientProfileService/Program.cs
new file mode 100644
index 0000000..2919489
--- /dev/null
+++ b/src/PatientProfileService/Program.cs
@@ -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((services, options) =>
+ options.UseNpgsql(services.GetRequiredService().GetConnectionString("PatientDatabase")));
+ builder.Services.AddScoped();
+ builder.Services.AddScoped();
+
+ 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().Database.MigrateAsync();
+ return;
+ }
+
+ app.UseExceptionHandler();
+ app.MapControllers();
+ await app.RunAsync();
+ }
+}
diff --git a/src/PatientProfileService/appsettings.json b/src/PatientProfileService/appsettings.json
new file mode 100644
index 0000000..2e95688
--- /dev/null
+++ b/src/PatientProfileService/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
+ }
+ }
+}
diff --git a/src/README.md b/src/README.md
index e69de29..1644886 100644
--- a/src/README.md
+++ b/src/README.md
@@ -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_`, 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.
diff --git a/suggestions/api-gateway-authentication.md b/suggestions/api-gateway-authentication.md
new file mode 100644
index 0000000..2393b4a
--- /dev/null
+++ b/suggestions/api-gateway-authentication.md
@@ -0,0 +1,5 @@
+# API gateway authentication policy
+
+The architecture assigns authentication and authorization to the API gateway, but the requirements do not define credentials, an identity provider, patient ownership, or which operations require authentication.
+
+US-01 is implemented without inventing access restrictions. Before implementing authentication, specify the identity mechanism, patient ownership relationship, and access policy for the existing API operations. This suggestion does not authorize an implementation or change the current requirements.
diff --git a/tests/PatientProfile.AcceptanceTests/CreatePatientTests.cs b/tests/PatientProfile.AcceptanceTests/CreatePatientTests.cs
new file mode 100644
index 0000000..ae804c1
--- /dev/null
+++ b/tests/PatientProfile.AcceptanceTests/CreatePatientTests.cs
@@ -0,0 +1,99 @@
+using System.Net;
+using System.Net.Http.Json;
+using System.Text;
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore;
+using Xunit;
+
+namespace PatientProfile.AcceptanceTests;
+
+public sealed class CreatePatientTests(PatientApiFixture fixture) : IClassFixture
+{
+ // This HTTP contract is independent of the service's implementation DTOs.
+ public sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
+
+ [Fact]
+ public async Task Valid_profile_is_assigned_an_identifier_and_can_be_retrieved_after_restart()
+ {
+ using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
+ {
+ name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "steffen@example.test"
+ });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ var created = await response.Content.ReadFromJsonAsync();
+ Assert.NotNull(created);
+ Assert.NotEqual(Guid.Empty, created.PatientId);
+ Assert.Equal("Steffen Example", created.Name);
+ Assert.Equal(new DateOnly(1980, 1, 1), created.DateOfBirth);
+ Assert.Equal("steffen@example.test", created.ContactInfo);
+ Assert.Equal($"/api/patients/{created.PatientId}", response.Headers.Location!.ToString());
+
+ await fixture.RestartHostsAsync();
+ using var retrieved = await fixture.Client.GetAsync(response.Headers.Location);
+ Assert.Equal(HttpStatusCode.OK, retrieved.StatusCode);
+ Assert.Equal(created, await retrieved.Content.ReadFromJsonAsync());
+
+ await using var db = fixture.CreateDbContext();
+ var stored = await db.Patients.SingleAsync(p => p.PatientId == created.PatientId);
+ Assert.Equal(created.Name, stored.Name);
+ Assert.Equal(created.DateOfBirth, stored.DateOfBirth);
+ Assert.Equal(created.ContactInfo, stored.ContactInfo);
+ Assert.NotEqual(default, stored.CreatedAt);
+ Assert.Equal(stored.CreatedAt, stored.UpdatedAt);
+ }
+
+ [Theory]
+ [InlineData("{\"dateOfBirth\":\"1980-01-01\"}", "Name")]
+ [InlineData("{\"name\":null,\"dateOfBirth\":\"1980-01-01\"}", "Name")]
+ [InlineData("{\"name\":\"\",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
+ [InlineData("{\"name\":\" \",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
+ [InlineData("{\"name\":\"Steffen Example\"}", "DateOfBirth")]
+ [InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":null}", "DateOfBirth")]
+ public async Task Missing_required_information_is_rejected_without_persisting(string json, string field)
+ {
+ await using var db = fixture.CreateDbContext();
+ var countBefore = await db.Patients.CountAsync();
+ using var content = new StringContent(json, Encoding.UTF8, "application/json");
+ using var response = await fixture.Client.PostAsync("/api/patients", content);
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.True(problem.RootElement.GetProperty("errors").TryGetProperty(field, out _));
+ Assert.Equal(countBefore, await db.Patients.CountAsync());
+ }
+
+ [Theory]
+ [InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"invalid\"}")]
+ [InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"1980-02-30\"}")]
+ [InlineData("{")]
+ public async Task Malformed_information_is_rejected(string json)
+ {
+ await using var db = fixture.CreateDbContext();
+ var countBefore = await db.Patients.CountAsync();
+ using var content = new StringContent(json, Encoding.UTF8, "application/json");
+ using var response = await fixture.Client.PostAsync("/api/patients", content);
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Equal(countBefore, await db.Patients.CountAsync());
+ }
+
+ [Fact]
+ public async Task Separate_creations_have_distinct_identifiers_and_contact_information_is_optional()
+ {
+ var request = new { name = "Steffen Example", dateOfBirth = "1980-01-01" };
+ using var first = await fixture.Client.PostAsJsonAsync("/api/patients", request);
+ using var second = await fixture.Client.PostAsJsonAsync("/api/patients", request);
+ Assert.Equal(HttpStatusCode.Created, first.StatusCode);
+ Assert.Equal(HttpStatusCode.Created, second.StatusCode);
+ var firstProfile = await first.Content.ReadFromJsonAsync();
+ var secondProfile = await second.Content.ReadFromJsonAsync();
+ Assert.NotEqual(firstProfile!.PatientId, secondProfile!.PatientId);
+ Assert.Null(firstProfile.ContactInfo);
+ Assert.Equal(firstProfile, await fixture.Client.GetFromJsonAsync(first.Headers.Location));
+ }
+
+ [Fact]
+ public async Task Unknown_identifier_returns_not_found()
+ {
+ using var response = await fixture.Client.GetAsync($"/api/patients/{Guid.NewGuid()}");
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+}
diff --git a/tests/PatientProfile.AcceptanceTests/PatientApiFixture.cs b/tests/PatientProfile.AcceptanceTests/PatientApiFixture.cs
new file mode 100644
index 0000000..06be495
--- /dev/null
+++ b/tests/PatientProfile.AcceptanceTests/PatientApiFixture.cs
@@ -0,0 +1,79 @@
+using Microsoft.AspNetCore.Hosting;
+using System.Net;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using Npgsql;
+using PatientProfileService.Persistence;
+using Xunit;
+
+namespace PatientProfile.AcceptanceTests;
+
+public sealed class PatientApiFixture : IAsyncLifetime
+{
+ private readonly string databaseName = "us01_" + Guid.NewGuid().ToString("N");
+ private string adminConnectionString = "";
+ private WebApplicationFactory? service;
+ private WebApplicationFactory? gateway;
+ public string ConnectionString { get; private set; } = "";
+ public HttpClient Client { get; private set; } = null!;
+
+ public async Task InitializeAsync()
+ {
+ adminConnectionString = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION")
+ ?? throw new InvalidOperationException(
+ "Set TEST_POSTGRES_CONNECTION to a PostgreSQL connection with permission to create test databases.");
+ await using var connection = new NpgsqlConnection(adminConnectionString);
+ await connection.OpenAsync();
+ await using var command = new NpgsqlCommand($"CREATE DATABASE {databaseName}", connection);
+ await command.ExecuteNonQueryAsync();
+ ConnectionString = new NpgsqlConnectionStringBuilder(adminConnectionString) { Database = databaseName }.ConnectionString;
+ await using var db = CreateDbContext();
+ await db.Database.MigrateAsync();
+ // Applying the committed migration twice must be harmless.
+ await db.Database.MigrateAsync();
+ StartHosts();
+ }
+
+ public PatientDbContext CreateDbContext() => new(
+ new DbContextOptionsBuilder().UseNpgsql(ConnectionString).Options);
+
+ private void StartHosts()
+ {
+ service = new WebApplicationFactory().WithWebHostBuilder(builder =>
+ {
+ builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
+ builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
+ new Dictionary { ["ConnectionStrings:PatientDatabase"] = ConnectionString }));
+ });
+ service.UseKestrel(0);
+ using var serviceClient = service.CreateClient();
+
+ gateway = new WebApplicationFactory().WithWebHostBuilder(builder =>
+ builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
+ new Dictionary { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString() })));
+ Client = gateway.CreateClient();
+ }
+
+ public async Task RestartHostsAsync()
+ {
+ Client.Dispose();
+ await gateway!.DisposeAsync();
+ await service!.DisposeAsync();
+ StartHosts();
+ }
+
+ public async Task DisposeAsync()
+ {
+ Client?.Dispose();
+ if (gateway is not null) await gateway.DisposeAsync();
+ if (service is not null) await service.DisposeAsync();
+ if (string.IsNullOrEmpty(adminConnectionString)) return;
+
+ NpgsqlConnection.ClearAllPools();
+ await using var connection = new NpgsqlConnection(adminConnectionString);
+ await connection.OpenAsync();
+ await using var command = new NpgsqlCommand($"DROP DATABASE IF EXISTS {databaseName} WITH (FORCE)", connection);
+ await command.ExecuteNonQueryAsync();
+ }
+}
diff --git a/tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj b/tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj
new file mode 100644
index 0000000..f945f2c
--- /dev/null
+++ b/tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj
@@ -0,0 +1,17 @@
+
+
+ net10.0
+ enable
+ enable
+ false
+ true
+
+
+
+
+
+
+
+
+
+