Files
HealthAppRepositoryB/Docs/AsBuiltArchitecture/software-architecture.md
T

292 lines
49 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HealthApp software architecture — as built
## 1. Scope and evidence
This is a source-level snapshot dated 2026-10-12 at commit `5d9371388c15066eeb2bc124ed227659c644dab5`. The system is a prototype REST backend for synthetic patient profiles, blood-pressure observations and derived assessments. It includes an installer and separate experiment tools. A web/mobile client is a context actor in the original diagrams; no product frontend is implemented in this repository.
Descriptions below are verified from source unless explicitly labelled inferred or unknown. Evidence links resolve to the inspected repository. Existing specifications supply context, especially [architecture authority](../Docs/Architecture/README.md), [common requirements](../Docs/Requirements/00-common-requirements.md), [Insights correction](../Docs/Architecture/us10-insights-correction.md) and [authentication design](../Docs/Design/authentication-and-access-control-design.md). Their differences from the implementation are catalogued in [discrepancies](discrepancies.md).
The [evidence inventory](evidence-inventory.md) records the inspected files. Automated tests were read, not rerun; this document makes no new test-pass, performance, clinical-validation or native-platform deployment claim.
## 2. Style, boundaries and structure
The implementation uses five independently buildable ASP.NET Core controller projects and operating-system processes. The topology is synchronous request/response microservices with a central API Gateway, service-owned persistence, and conventional controller/application/repository layering in the two persistent services. There is no application message bus, event processing, background synchronization or shared production implementation library. See [solution](../HealthApp.slnx), [logical diagram](diagrams/02-logical-services.drawio) and each service's `Program.cs` below.
| Process / project | Responsibility | Local implementation | State |
| --- | --- | --- | --- |
| [ApiGateway](../src/ApiGateway/Program.cs) | Client login, token authentication, ownership/assignment authorization, explicit API forwarding, public guidance | Controllers, security middleware, framework authentication and named HTTP clients | Startup account/assignment configuration; persistent token-protection key files |
| [PatientProfileService](../src/PatientProfileService/Program.cs) | Initial profile/account association, profile reads and updates | Controller → scoped application service → repository interface → SQL repository → EF context | Own PostgreSQL database, `patient` table |
| [ObservationService](../src/ObservationService/Program.cs) | Record/read/latest/history/correct/delete observations and their context | Controller → scoped application service → repository interface → SQL repository → EF context; gateway HTTP client for patient existence | Own PostgreSQL database, `blood_pressure_observation` table |
| [InsightsService](../src/InsightsService/Program.cs) | On-demand numerical summaries and context-aware trend assessment | Controller → scoped application service → observation HTTP client and singleton stateless calculator | No database or generated-result persistence |
| [HealthOverviewService](../src/HealthOverviewService/Program.cs) | Compose profile, latest overall observation and selected-period numerical insight | Controller → scoped application service → three typed HTTP clients | No database or generated-result persistence |
Every business call between services passes through the Gateway. The Gateway sends `X-Gateway-Key` to a target service; Observation, Insights and Overview call the Gateway using their own `X-Service-Key`. The Patient/Profile service has no outgoing business HTTP dependency. There are no direct Insights→Observation or Overview→Patient/Profile network calls: client class names denote the resource consumed, while their configured origin is the Gateway. This matches the [original service topology](../Docs/Architecture/02_microservice_architecture.jpg).
Within a service, dependencies are ordinary dependency injection calls. Between services, dependencies are actual HTTP/JSON calls; production projects do not reference each other's implementations. Tests do reference multiple projects and create hosts in one test runner, which is a testing arrangement, not the deployed process model.
The separate [HealthApp.Provisioning](../deploy/HealthApp.Provisioning/Program.cs) executable prepares deployment material, provisions databases and verifies the installed system. It is an administrative utility, not an additional microservice. [PasswordHash](../tools/PasswordHash/Program.cs) is another standalone utility for hashing input passwords, outside the solution's service topology.
## 3. Domain and ownership
The [domain diagram](diagrams/03-domain-model.drawio) uses business concepts, while [class diagrams](diagrams/04-design-classes.drawio) use actual implementation types.
The complete domain view includes authentication grants, professional assignments, guidance instructions and reference provenance as well as profiles, observations and calculated views. Deployment administration has a separate supporting-domain page. Each service also has its own implementation class-diagram file, linked from [README](README.md). Each declared class, record and interface is an individual UML classifier, including nested records, startup and generated EF support types. [Class-diagram coverage](class-diagram-coverage.md) maps all 78 source types and explains visibility, members and relationship notation.
A pre-created **account** identifies a Patient or HealthcareProfessional. A Patient account has zero associated profiles initially and one after creation. A **patient profile** has a generated identifier, name, date of birth and optional contact information. The association is persisted in the profile's row, separate from credential configuration. Legacy rows can have null account association.
A **blood-pressure observation** belongs to one patient by external patient identifier. It records measurement time, systolic/diastolic pressure, device-reported pulse, original free-text context and note, and one structured **measurement context**. Setting and activity categories remain independent; missing values become `Unknown`. Optional preparation/technique details remain unknown/null rather than being inferred from legacy text. Context has no independent persisted identifier or lifecycle.
A **context selection** optionally restricts setting and/or activity. Both supplied dimensions must match; omitted dimensions are unrestricted. An explicit `Unknown` is a filter value, not omission. A **health insight** summarizes current selected observations. A **trend assessment** contains separate systolic, diastolic and pulse assessments plus comparability evidence. A **health overview** combines a profile, optional latest observation and optional numerical insight. These are calculated values, not stored domain entities.
HealthcareProfessional **assignments** form a configured many-to-many account/patient relationship. No professional profile or assignment table exists. General **measurement guidance** has no patient association and does not write observations.
Evidence: [Patient](../src/PatientProfileService/Domain/Patient.cs), [observation](../src/ObservationService/Domain/BloodPressureObservation.cs), [measurement context](../src/ObservationService/Domain/MeasurementContext.cs), [selection](../src/ObservationService/Domain/ContextSelection.cs), [insight](../src/InsightsService/Domain/HealthInsight.cs), [trend types](../src/InsightsService/Domain/TrendAssessment.cs), [overview contracts](../src/HealthOverviewService/Contracts/HealthOverviewDto.cs), [assignments](../src/ApiGateway/Security/ProfessionalAssignments.cs).
## 4. Public API and contracts
All routes below are exposed by Gateway controllers. IDs are GUID route values. JSON uses the standard ASP.NET Core serializer conventions. Authentication applies to patient-specific routes; professionals can only read assigned patients, and only professionals can list their own assignments.
| Method and route | Input / result | Owning component |
| --- | --- | --- |
| `POST /api/authentication/login` | Required `accountId`, `password`; 200 access token, token type, lifetime, account ID, role; invalid credentials 401 | Gateway |
| `GET /api/measurement-guidance` | Optional setting/activity; 200 ordered guidance or explained unavailability; unsupported values 400 | Gateway; public |
| `GET /api/professionals/me/patients` | 200 array of `{patientId}` assignments, possibly empty | Gateway |
| `POST /api/patients` | Required name/dateOfBirth, optional contactInfo; 201 profile and Location; existing profile 409 | Patient/Profile |
| `GET /api/patients/me` | 200 authenticated account's profile; unavailable 404 | Patient/Profile via Gateway account lookup |
| `GET /api/patients/{patientId}` | 200 profile; missing/unauthorized owner 404 | Patient/Profile |
| `PUT /api/patients/{patientId}` | Required name, optional contactInfo; 200 updated profile; date of birth is not editable | Patient/Profile |
| `POST /api/patients/{patientId}/observations` | Required measuredAt and positive integer systolic/diastolic/pulse; optional structured context, context text and note; 201 observation and Location | Observation |
| `GET /api/observations/{observationId}` | 200 observation with recorded context; unavailable 404 | Observation |
| `PUT /api/observations/{observationId}` | All three positive measured values required; 200 corrected observation; other fields preserved | Observation |
| `PATCH /api/observations/{observationId}` | At least one supported measured/context/note field; 200 patched observation | Observation |
| `DELETE /api/observations/{observationId}` | 204 deleted; unavailable 404 | Observation |
| `GET /api/patients/{patientId}/observations/latest` | 200 latest overall observation; none 404 | Observation |
| `GET /api/patients/{patientId}/observations` | Required from/to, optional context selection; 200 array, empty `[]` allowed | Observation |
| `GET /api/patients/{patientId}/insights` | Required from/to, optional context selection; 200 numerical insight; no matching data 404 Problem | Insights |
| `GET /api/patients/{patientId}/trends` | Same query; 200 assessment, including explicit unavailable parts for empty/insufficient data | Insights |
| `GET /api/patients/{patientId}/overview` | Same query applied to insight only; 200 overview with nullable latest/insight; missing patient 404 Problem | Overview |
Gateway route evidence: [Patient](../src/ApiGateway/Controllers/PatientController.cs), [Observation](../src/ApiGateway/Controllers/ObservationController.cs), [Insights](../src/ApiGateway/Controllers/InsightsController.cs), [Overview](../src/ApiGateway/Controllers/HealthOverviewController.cs), [Professional](../src/ApiGateway/Controllers/ProfessionalController.cs), [Authentication](../src/ApiGateway/Controllers/AuthenticationController.cs), [Guidance](../src/ApiGateway/Controllers/MeasurementGuidanceController.cs). Backend-specific statuses/validation are defined by the corresponding controllers and contracts, not by a general reverse-proxy engine.
### 4.1 Forwarding and internal contracts
Gateway forwarding constructs a new HTTP request with a configured target and key. It streams POST/PUT/PATCH bodies and forwards Content-Type, not arbitrary client headers. It does not forward client tokens, client-selected account identities or callback keys. Profile creation explicitly derives `X-Account-Id` from the authenticated claim. Response forwarding preserves status, Content-Type and Location (absolute locations are reduced to path/query). Observation forwarding also preserves `X-Measurement-Setting` and `X-Activity-Condition`. The rest of upstream headers are not generically copied. Redirect following is disabled on all configured business HTTP clients.
Backend endpoints mostly mirror the Gateway routes. Patient/Profile additionally exposes `GET /api/patients/by-account/{accountId}` behind its key boundary; Gateway uses it internally and does not expose a corresponding controller route. `/api/patients/me`, login, guidance and assignment listing are Gateway-owned routes.
DTOs are defined locally within each service; consumers deserialize equivalent wire shapes without shared service project references. Insights duplicates an observation/context DTO; Overview duplicates patient, observation, insight and selection DTOs. These are structural JSON contracts, not references to remote domain objects. There is no OpenAPI/Swagger endpoint, API-versioning mechanism or generated client in the application setup.
### 4.2 Validation, patch and period semantics
`[ApiController]`, data annotations and JSON parsing reject invalid model input with 400 validation details. Categories are case-sensitive for recording/filtering/patching: settings `Home`, `Clinic`, `Other`, `Unknown`; activities `AtRest`, `DuringActivity`, `AfterActivity`, `Unknown`. General guidance trims and compares categories without case sensitivity. Numeric observation values must be positive integers; optional rest duration is a nonnegative decimal in minutes. There are no documented clinical upper/lower plausibility checks beyond those input constraints.
PATCH uses setter-maintained `...Specified` flags marked `[JsonIgnore]`. Omitted fields remain unchanged; explicit null clears optional text/details; null setting/activity becomes `Unknown`; null entire context resets it to unknown categories/null details. Numeric values cannot be cleared. Empty or unknown-field patches are rejected. Observation PUT accepts only the three numerical fields and rejects unmapped fields. Profile update preserves identifier, birth date, original creation time and account association; omitted/null contact information clears it. These behaviors are implemented in [patch contracts](../src/ObservationService/Contracts/PatchObservationRequest.cs), [context patch](../src/ObservationService/Contracts/MeasurementContextPatch.cs), [PUT contract](../src/ObservationService/Contracts/UpdateObservationRequest.cs) and [repositories](../src/ObservationService/Persistence/SqlObservationRepository.cs).
Period boundaries are inclusive. Reversed bounds are rejected; equal bounds are valid. Offset-free timestamp values are interpreted as UTC clock values, independent of host timezone. Offset-bearing values are normalized to UTC and stored as `DateTimeKind.Unspecified` in PostgreSQL `timestamp without time zone`. Responses therefore need not contain a trailing `Z`; clients must retain the documented UTC interpretation. `DateOnly` represents birth dates. Evidence: [record/period normalization](../src/ObservationService/Application/ObservationApplicationService.cs), [Insights normalization](../src/InsightsService/Application/InsightsApplicationService.cs), [Overview normalization](../src/HealthOverviewService/Application/HealthOverviewApplicationService.cs), [implementation timestamp documentation](../src/README.md), [offset/boundary tests](../tests/Observation.AcceptanceTests/ContextFilteredHistoryTests.cs).
## 5. Persistence and consistency
See [data diagram](diagrams/05-data-ownership.drawio). Each persistent service has a scoped EF Core DbContext and SQL repository. Reads generally use `AsNoTracking`; observation patches load a tracked entity and save it. Patient updates use `ExecuteUpdateAsync`, observation deletes use `ExecuteDeleteAsync`. There is no shared database access between application services.
| Owner/table | Columns and constraints |
| --- | --- |
| Patient/Profile `patient` | `patient_id uuid` PK generated by application; `account_id text NULL` with unique index `IX_patient_account_id`; required `name varchar`, `date_of_birth date`; optional `contact_info varchar`; required `created_at`, `updated_at timestamp without time zone` |
| Observation `blood_pressure_observation` | `observation_id uuid` PK generated by application; external `patient_id uuid`; `measured_at timestamp without time zone`; integer `systolic`, `diastolic`, `pulse`; optional `context`, `note varchar`; required original/update timestamps; required text `setting`, `activity_condition` default `Unknown`; nullable numeric `rest_duration_minutes` and text body position/arm/device/cuff/circumstances |
| Each EF-owned database | Framework `__EFMigrationsHistory`; no patient/observation cross-database foreign key |
`MeasurementContext` is an EF owned value flattened into the observation row. There is no separate context/preparation table. Database mappings declare PKs and the account uniqueness index, but no observation patient/time/filter indexes or category/positive-value check constraints. Input validation is enforced by APIs/application services; database credentials remain a separate trust boundary.
Evidence: [PatientDbContext](../src/PatientProfileService/Persistence/PatientDbContext.cs), [ObservationDbContext](../src/ObservationService/Persistence/ObservationDbContext.cs), [profile initial migration](../src/PatientProfileService/Persistence/Migrations/20260930200031_InitialPatientSchema.cs), [association migration](../src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.cs), [observation initial migration](../src/ObservationService/Persistence/Migrations/20261001095222_InitialObservationSchema.cs), [context migration](../src/ObservationService/Persistence/Migrations/20261005094632_RecordedMeasurementContext.cs).
### 5.1 Profile creation
Profile creation and account association are a single row insert. The application checks for an existing account first, but the unique database index is the final concurrency guard. A conflicting PostgreSQL `23505` for that index is translated into `ProfileAlreadyExistsException` and 409. Database failure leaves no separate association step to recover; a lost successful response followed by retry returns the existing-profile conflict, and `/api/patients/me` retrieves the association. Legacy null-account rows remain possible, with no automatic credential association/backfill.
Evidence: [application](../src/PatientProfileService/Application/PatientApplicationService.cs), [repository](../src/PatientProfileService/Persistence/SqlPatientRepository.cs), [concurrency/retry/trigger rollback tests](../tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs).
### 5.2 Observation queries and changes
Recording first verifies patient existence by Observation→Gateway→Patient/Profile. Only then does it save the observation in its own database. This is not a distributed transaction or database foreign key. There is no patient deletion endpoint, but the runtime lookup and write still occur at different instants.
Latest orders by descending measurement time, then original `created_at`, then observation UUID under PostgreSQL ordering. Edits never update original recording time. History filters one patient, inclusive period and both requested context predicates; it orders measurement time ascending then UUID ascending. It returns all matching rows as a list with no pagination or result-size cap. Patch updates preserve omitted values; physical deletion removes the row and all its flattened context.
New insights/trends/overviews read current data. No invalidation event is needed because no generated result is stored. This does **not** imply a cross-service snapshot: overview profile, latest and insight are separate reads. A write between them can produce a composition from different instants.
## 6. Calculation and aggregation behavior
### 6.1 Numerical insight
Insights requests filtered history through the Gateway and calculates arithmetic decimal means for systolic/diastolic/pulse; only final means are rounded to two decimals, midpoint away from zero (half-up for the permitted positive inputs). Blood-pressure minima/maxima retain original integer values. One observation suffices. Zero returns no insight and a 404 Problem; it is not an upstream failure.
The response includes patient, normalized period, applied selection, contributing count and descriptive context explanation. Mixed/unknown settings, activities and optional details are disclosed. Source data is neither relabelled nor persisted by Insights. Evidence: [summary calculator](../src/InsightsService/Domain/InsightCalculator.cs), [HTTP observation client](../src/InsightsService/Clients/HttpObservationServiceClient.cs), [summary tests](../tests/Observation.AcceptanceTests/ContextSelectedInsightTests.cs).
### 6.2 Trends and comparability
Each metric retains mean/min/max/range over every selected raw observation. Temporal calculations group identical measurement timestamps into arithmetic means, then sort by timestamp. At least two distinct timestamps are needed for direction. Adjacent nonzero changes determine Increasing, Decreasing, Mixed or NoClearDirection; sign changes count reversals. Total successive change sums absolute adjacent changes. An ordinary least-squares fit across all distinct timestamp means supplies OverallDirection and SlopePerDay; each timestamp group has equal weight. Time is scaled to the observed span for calculation; slope output is rounded to six decimals. Empty or single-timestamp data returns explicit unavailable portions, not fabricated direction.
Recorded comparability inspects setting/activity/rest/posture/arm/device/cuff similarities, missing details and differences, plus differing additional circumstances. A finite list of case-insensitive narrative phrases detects conflicts between declared Home/Clinic/AtRest and preserved text. This is deterministic phrase matching, not NLP; unrecognized text does not establish correctness, and negations can still match.
The compiled reference metadata supports resting pulse comparisons below 50 or above 100 beats/min, and high blood-pressure comparisons at or above home 135/85 or clinic 140/90 mmHg. Blood-pressure reference selection requires a single known Home/Clinic setting and recorded AtRest, without detected conflicts or explicitly inadequate rest/posture. Missing preparation details can permit a limited provisional reference comparison. These figures describe the **implemented reference selection**, not new medical advice or an independent verification of the sources.
Interpretation distinguishes supported numerical findings from cautiously labelled PotentiallyFavourable, PotentiallyConcerning, Mixed or CannotInterpret. It requires additional comparability/temporal support for development interpretations, never combines the three metrics into one good/bad score, and includes reference scope, operators, sources, dates and limitations. Current guidance/reference text is compiled into the application; no clinical website is called at runtime.
Evidence: [trend calculator](../src/InsightsService/Domain/InsightCalculator.Trends.cs), [result types](../src/InsightsService/Domain/TrendAssessment.cs), [documented method/rationale](../src/TRENDS.md), [numerical/context/reference tests](../tests/Observation.AcceptanceTests/HealthTrendTests.cs). This task checks architectural consistency, not clinical validity.
### 6.3 Health overview
Overview performs three **sequential** awaits: profile, latest overall observation, selected-period numerical insight. A missing profile returns no overview; a 404 latest or insight becomes null and preserves the available profile/other component. Non-404 failures do not silently become absent data. Latest remains independent of the insight's period and context selection. The result explicitly states both bases and contributes no trend component.
The insight request adds another chain: Overview→Gateway→Insights→Gateway→Observation. Each network leg uses the caller's configured service credential; original user tokens do not flow down the chain. Evidence: [overview application](../src/HealthOverviewService/Application/HealthOverviewApplicationService.cs), [client handling](../src/HealthOverviewService/Clients/InsightsServiceClient.cs), [overview tests](../tests/Observation.AcceptanceTests/HealthOverviewTests.cs), [overview sequence](diagrams/07-sequences.drawio).
## 7. Authentication, authorization and security
### 7.1 Client identity
Gateway validates pre-created credentials using ASP.NET Core Identity's `PasswordHasher<PrototypeAccount>`. Accounts are external configuration bound once into a singleton dictionary. Roles are limited to Patient and HealthcareProfessional; account IDs permit ASCII letters/digits/hyphen/underscore, with a maximum length of 128. Unknown accounts still execute hash verification against a dummy hash. Invalid/incorrect credentials share one generic response. Malformed hash verification is rejected; successful hashes that would benefit from rehashing are not persisted back to configuration.
Login issues the framework's protected opaque Bearer authentication ticket, **not a JWT**, using Data Protection application name `HealthApp.ApiGateway`. Claims contain stable account ID and role, not patient health records or patient ownership. Default lifetime is 30 minutes, configurable from 1–1440. Subsequent requests validate the token without password verification. There is no refresh, logout/revocation endpoint, session database, registration or identity-provider integration. Successful login responses carry `no-store` and `no-cache`.
Gateway persists its Data Protection key ring to configured `Authentication:KeyDirectory`. No explicit `ProtectKeysWith...` key-at-rest encryption is configured; filesystem permissions are the deployment protection visible in this implementation. Persistent compatible keys allow tokens to survive a normal Gateway restart. Multi-instance Gateway key coordination, immediate account-change token revocation and external identity-provider behavior are not implemented or verified. See [accounts](../src/ApiGateway/Security/PrototypeAccounts.cs), [login](../src/ApiGateway/Controllers/AuthenticationController.cs), [Gateway startup](../src/ApiGateway/Program.cs), [authentication tests](../tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs).
### 7.2 Per-request access control
Fallback authorization requires authentication; login and general guidance explicitly permit anonymous callers. Role policies require the stable NameIdentifier claim. `PatientAccessMiddleware` then establishes actual access:
- A Patient can POST its initial profile and GET `/api/patients/me` before knowing its patient ID. The profile service enforces uniqueness.
- Other patient operations obtain the account's current persisted profile through the protected by-account API. Requested patient routes must match its ID.
- Observation-ID routes first fetch the observation from Observation to establish the actual owning patient. This additional read occurs before returning/modifying/deleting it.
- Professionals may only GET and must have the patient ID in their configured assignment set. The assignment-list route returns only that professional's configured IDs. Assignments are read once, deduplicated and sorted; edits require restart to affect the singleton.
- Unauthorized ownership/unassigned/missing ownership gives an empty 404 to avoid exposing another patient's existence. Missing/invalid token is 401; authenticated forbidden role/method is 403.
Ownership data is not cached between requests. Patient-specific responses do not receive a global explicit no-store directive in the code. Middleware path-segment comparisons are case-sensitive, despite routing's normal case-insensitive behavior and a few case-insensitive special routes; canonical lower-case routes are used throughout tests/clients. Evidence: [middleware](../src/ApiGateway/Security/PatientAccessMiddleware.cs), [assignments](../src/ApiGateway/Security/ProfessionalAssignments.cs), [professional tests](../tests/Observation.AcceptanceTests/ProfessionalAccessTests.cs), [replacement-handler test](../tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs).
### 7.3 Internal trust boundary
Every backend checks `X-Gateway-Key` with fixed-time comparison before controllers. A client bearer token alone cannot call a backend. The key grants the Gateway-level trusted caller boundary; backend controllers do not re-evaluate patient ownership or professional assignment. Compromise/disclosure of a backend incoming key therefore bypasses client authorization for that backend's exposed API.
Gateway chooses InternalService authentication whenever `X-Service-Key` is present; otherwise it chooses Bearer. An invalid callback key does not fall back to a valid bearer token. Three distinct configured callback identities have the following GET-only permissions:
| Callback identity | Allowed Gateway reads |
| --- | --- |
| Observation | `/api/patients/{patientId}` |
| Insights | `/api/patients/{patientId}/observations` with period/selection query |
| HealthOverview | Patient profile, latest observation and numerical insight for `{patientId}` |
Service identities do not carry end-user ownership; permitted reads can address any valid patient ID. They cannot write, list professional assignments, read individual observation IDs or call unlisted aggregation routes. Backend incoming and callback keys are independently generated; length ≥32 is required at startup, while installer-generated secrets are 32 random bytes rendered as 64 hex characters. The unused incoming-key field generated for Gateway is not a Gateway authentication mechanism.
Evidence: [internal handler](../src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs), [service whitelist](../src/ApiGateway/Security/PatientAccessMiddleware.cs), [backend guard example](../src/ObservationService/Program.cs), [bypass/permission tests](../tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs), [Overview restrictions](../tests/Observation.AcceptanceTests/HealthOverviewTests.cs).
### 7.4 Transport and secrets
Non-Development modes require HTTPS business origins. Plain HTTP is rejected with 400 by Gateway and 401 by backends; requests are not redirected to HTTPS. Development permits HTTP for local tests/development while still requiring authentication keys. Base origins must be absolute HTTP(S), root-path URLs without userinfo, query or fragment. There is no application mTLS, forwarded-header trust setup, CORS configuration or rate limiter.
The installer configures Kestrel PFX certificates and OS trust. Client machines independently need trust in the exported public CA or a supplied trusted certificate chain. Server certificates authenticate endpoint names; internal application keys authenticate callers. PostgreSQL-generated connections use `SslMode=Prefer`, not mandatory verified TLS, and default to local database hosts. This is a different boundary from mandatory production HTTPS between application processes.
Generated deployment manifests/account files contain secrets and are protected administratively. Linux uses private deployment files/root-readable environment files and service-group-readable certificates; Windows ACLs and macOS permissions are described below. Application logging uses framework logging/stdout/stderr. No explicit sensitive-data logging is enabled, but request paths can contain patient/observation identifiers. No audit-log store or patient-data log redaction facility is implemented. These are observable limits, not an expansion of the prototype's stated scope.
## 8. Concurrency, caching and runtime behavior
ASP.NET handles concurrent HTTP requests; database and network work uses async Task/CancellationToken. Scoped application services/repositories/contexts are per request. The singleton calculator has no mutable per-request state; accounts/assignments are startup snapshots. Gateway re-entrant callback HTTP traffic is handled as new requests, not recursive in-process calls. Inferred consequence: aggregate workflows add Gateway hops and dependent-service load even when only one external request is counted.
There is no application response/data cache, output-cache middleware, distributed cache, stored statistics or materialized view. Static guidance and loaded account/assignment dictionaries are configuration/reference state rather than caches of clinical data. Framework HTTP handler reuse and database connection behavior are separate infrastructure concerns. The generated database connection strings explicitly set `Pooling=false` and a 10-second connection timeout; externally supplied connection strings can choose different settings. No business HttpClient timeout override or resilience/retry/circuit-breaker policy is configured. The verifier's retry policy does not apply to ordinary application requests.
Profile creation uniqueness is explicitly concurrency-safe. Other updates have no EF concurrency token, version/ETag or conditional-write contract. Inferred: concurrent edits can overwrite each other's changes, especially owned context replacement after reading its previous value; the read following a profile update can observe a later writer's values. There is no multi-service transaction, request idempotency key for observation creation or guaranteed atomic overview snapshot.
History and calculation clients materialize full matching arrays in memory. Overview awaits sources sequentially rather than parallelizing them. Request cancellation is passed through normal HTTP/database operations; connection/HTTP timeouts can happen independently, and client-disconnect cancellation is not deliberately converted to 504.
Runtime evidence: all five `Program.cs` files, [Observation repository](../src/ObservationService/Persistence/SqlObservationRepository.cs), [Patient repository](../src/PatientProfileService/Persistence/SqlPatientRepository.cs), [overview application](../src/HealthOverviewService/Application/HealthOverviewApplicationService.cs), [connection-string generation](../deploy/HealthApp.Provisioning/Deployment.cs).
## 9. Deployment architecture and dependencies
### 9.1 Build and runtime
All five service projects target `net10.0`. Services include `Microsoft.Extensions.Hosting.WindowsServices` 10.0.12. The persistent services use Npgsql EF provider 10.0.3 and EF Relational/Design 10.0.12; Design is private tooling. Provisioning uses Npgsql 10.0.3 and the ASP.NET shared framework. Versions are those declared by the inspected project files, not a latest-version recommendation. xUnit, ASP.NET testing support and PostgreSQL are acceptance-test dependencies.
[build-release.sh](../deploy/build-release.sh) and [build-release.ps1](../deploy/build-release.ps1) publish selected projects separately in Release, framework-dependent (`--self-contained false`) without an apphost (`UseAppHost=false`), plus the provisioner. The bundle carries installer scripts, systemd templates, safe examples and installation documentation. Build requires .NET 10 SDK and package access. Target machines require the .NET 10 ASP.NET Core runtime and PostgreSQL only for persistent services; automatic provisioning supplies missing supported dependencies.
### 9.2 Topology and configuration
Colocated and distributed layouts use the same DLLs and HTTP interfaces. [deployment diagrams](diagrams/06-deployment.drawio) show both supported layouts, not a claim about current physical hosts. Defaults are Gateway HTTPS 5443 and Patient/Profile/Observation/Insights/Overview HTTPS 5081/5082/5083/5084. Generated bindings are `https://0.0.0.0:PORT`; origins and certificate names use configured hosts. Ports must be 1024–65535; services at the same literal host need different ports. IPv6-reachable binding behavior and alias equivalence are not explicitly tested by this documentation task.
Standard .NET configuration loads JSON, environment and command-line values. Committed `appsettings.json` contains logging only. Required external values are:
| Service | Configuration |
| --- | --- |
| Gateway | `Authentication:Accounts`, `Authentication:KeyDirectory`, optional token lifetime; `Access:ProfessionalAssignments`; four `Services:{name}:BaseUrl/Key`; callback keys `InternalAccess:{Observation,Insights,HealthOverview}:Key` |
| Patient/Profile | `ConnectionStrings:PatientDatabase`, `InternalAccess:GatewayKey` |
| Observation | `ConnectionStrings:ObservationDatabase`, incoming Gateway key, `Services:ApiGateway:BaseUrl/Key` |
| Insights and Overview | Incoming Gateway key, `Services:ApiGateway:BaseUrl/Key`; no database settings |
| Each HTTPS host | Binding plus `Kestrel:Certificates:Default:Path/Password`, environment |
Environment-file keys use `__` for configuration sections. Missing/invalid required origins, keys, accounts and connection strings stop startup; startup validation is not a dependency reachability check. Patient/Profile and Observation support `--migrate`: migrations run and the process exits before normal host security/origin startup checks. Normal startup never migrates.
### 9.3 Provisioning stages
1. Validate selected service names, payloads and absence of existing installation/configuration. A repeated first-install command refuses overwrite; no upgrade/uninstall engine exists.
2. Detect supported native platform/dependencies. Linux accepts Debian/Ubuntu `ID`/`ID_LIKE`, apt and running systemd/root access. Package availability, not fixed release numbers, controls provisioning. Only actual Debian can receive a Microsoft Debian runtime repository fallback. Required package names are `aspnetcore-runtime-10.0` and, where needed, `postgresql`.
3. Prepare one private plan covering all five services, even for a subset. Generate per-service keys, database settings for the two owners, synthetic `prototype-patient`, `prototype-professional`, `installation-check` accounts and hashed Gateway account config. The professional initially has no assignments.
4. Generate a prototype CA (two-year validity) and service-name/IP SAN certificates (one-year validity). Only public CA material is retained; its generated signing private key is disposed. Alternatively accept externally supplied public CA and all service PFX/password files. Supplied material is not preflighted against every runtime requirement; endpoint verification checks trust/name later.
5. Create selected persistent services' separate DBs/roles, revoke public database/schema access and give the owner schema rights for migrations. Reuse a consistent generated plan, not independently generated incompatible secrets. Database roles cannot administer/create databases/roles/replicate. An external PostgreSQL admin connection can be supplied; generated service endpoint settings adopt its host/port.
6. Install selected payloads, protected configuration/certificates, native identities and registrations; apply migrations and start each selected process.
7. Verify local native status/distinct PIDs where implemented, HTTPS reachability, DB service identity, callback credentials and topology. Complete-system verification logs in and creates/reuses a labelled synthetic check profile/observation, then retrieves overview through all five services. Verification is therefore not entirely read-only.
Evidence: [Linux installer](../deploy/installer/install.sh), [bootstrap](../deploy/installer/bootstrap.sh), [deployment preparation](../deploy/HealthApp.Provisioning/Deployment.cs), [DB provisioning](../deploy/HealthApp.Provisioning/DatabaseProvisioning.cs), [config adapter](../deploy/HealthApp.Provisioning/ConfigurationWriter.cs), [verifier](../deploy/HealthApp.Provisioning/InstallationVerification.cs).
### 9.4 Native execution and paths
| Platform | Runtime management and paths | Important boundaries |
| --- | --- | --- |
| Linux | `healthapp-NAME.service`; `/opt/healthapp/NAME`; `/etc/healthapp/NAME/service.env`; Gateway `/var/lib/healthapp-api-gateway/keys`; default plan `/var/lib/healthapp-installation/deployment` | Dedicated `healthapp-NAME` users/groups; env root-only, certificates root/service group; systemd supplies env; default local PostgreSQL |
| Windows | Independent Windows Services/virtual `NT SERVICE\healthapp-NAME` identities; `%ProgramData%\HealthApp` with services/config/state | Private administrative ACLs plus own-service read/state rights; production JSON copied into application directory; selected HTTPS firewall rules; runtime downloaded if absent; EDB PostgreSQL 17 installer resolved from maintained package manifest and SHA-256 checked |
| macOS | Independent launchd daemons/hidden `_healthapp_NAME` identities; `/Library/Application Support/HealthApp` with services/config/state | System-keychain CA trust; Homebrew PostgreSQL 17 and installer-owned cluster if no external server; Apple command-line tools/Homebrew provisioning; private plist contains environment secrets |
Systemd source templates still show a shared `healthapp` user and old flat env paths. The installer rewrites them to per-service identities and nested env paths; the generated units are the as-built installed behavior. Units request network-online, restart on failure after five seconds, use SIGINT and a 30-second stop timeout. They do not couple peers via Requires/PartOf/BindsTo or impose explicit resource limits/sandbox directives. Backend DB unavailability does not necessarily stop a host before its first DB request. Independent stopping means process independence, not availability of workflows that depend on it.
Windows uses standard WindowsServices lifetime integration and restart-on-failure configuration. macOS `RunAtLoad`/`KeepAlive` launchd registration keeps daemons alive. The repository supplies a manual [native-install workflow](../.github/workflows/prototype-native-install.yml); its existence is not evidence that Windows/macOS live registration or CI execution succeeded.
### 9.5 Distributed administration and verification limits
One prepared topology can be grouped by host and installed through SSH/SCP using [Distribution](../deploy/HealthApp.Provisioning/Distribution.cs). Each node receives selected applications/private material and necessary remote origins, not all unrelated keys/DB passwords. The Gateway legitimately needs outgoing backend keys and callback authentication keys. Unix installation needs administrative SSH with noninteractive sudo; Windows requires an elevated SSH session. Host-administration access is a prerequisite separate from generated application credentials.
Node startup can defer cross-topology verification until other hosts start. Final verification probes actual origins. There is no remote runtime file-sharing dependency after installation. Failed installation retains existing/generated material and reports the failed step; it has no cross-host rollback transaction or remote-artifact cleanup guarantee. Linux `--root` is offline staging, not live package/service deployment.
Verification contains short startup retry loops for transient 502/503/504/connectivity failures, uses custom-root TLS validation with server-name checking, and tests actual database identity. Linux installer/verifier checks native active state and distinct MainPID values. Neither live verifier deliberately cycles every service through stop/restart. Independent stop/restart is exercised by deployment acceptance tests, with direct process control; native manager execution is a separate evidence limit. See [traceability](requirements-traceability.md).
## 10. Failure behavior
| Trigger | Implemented outcome |
| --- | --- |
| Missing/malformed model, unsupported category, reversed/missing period | 400 validation response; no intended partial write |
| Invalid login / missing, forged or expired bearer | 401; invalid login response does not identify which credential failed |
| Incorrect backend incoming key / production backend HTTP | 401 before controller |
| Production Gateway HTTP | Empty 400, including public/login routes |
| Forbidden professional write, role or internal service route | 403 |
| Cross-patient ownership, unassigned patient, no own profile, absent observation | Generally empty Gateway 404; authorized missing backend resources follow their own API response |
| Second/concurrent profile creation | 409 existing-profile condition, protected by unique DB index |
| No history / summary / temporal data | History 200 `[]`; summary 404 insufficient data; trends 200 explicit unavailable parts; overview keeps available profile/latest with null insight |
| Gateway forwarding connection failure | 502 Problem; upstream status responses otherwise forwarded |
| Local non-client-cancelled upstream timeout | 504 Problem; an upstream 504 already received remains an upstream response and can be mapped by a consuming service |
| Observation patient-lookup failure | 502/504, no saved observation |
| Insights/Overview upstream non-success or malformed JSON | 502; a local timeout 504; appropriate 404 treated as absence only in Overview clients |
| Ownership lookup invalid JSON/missing expected field, unhandled DB error or other exception | Generic exception-handler path, normally 500; not all invalid upstream shapes have an explicit 502 mapping |
| Gateway stream fails after response has started | Connection aborted; response cannot be replaced safely with a new error body |
| Required config invalid / packages unavailable / certificate or provisioning failure | Startup or installer fails; step diagnostics; retained data/material rather than automatic rollback |
Every host installs `AddProblemDetails`/`UseExceptionHandler`; response shapes are not entirely uniform (empty status responses, login `{title}`, validation Problems and explicit Problems coexist). Overview interprets any 404 from its designated insight route as absent insight; it does not inspect the upstream problem title to distinguish all possible causes. Gateway ownership lookup is an extra availability dependency on Patient/Profile for patient requests, even when the requested operation is otherwise Observation- or Insights-owned.
No automatic business retry, circuit breaker, overload shedding, rate limit, dedicated readiness/liveness API or fault-tolerant replica configuration is implemented. Inferred: a Gateway outage prevents all normal external operations and aggregation callbacks; a source outage may leave peer processes running while dependent workflows fail. Runtime failure tests: [patient failures](../tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs), [insight failures](../tests/Observation.AcceptanceTests/HealthInsightTests.cs), [trend failures](../tests/Observation.AcceptanceTests/HealthTrendTests.cs), [overview failures](../tests/Observation.AcceptanceTests/HealthOverviewTests.cs).
## 11. Test and experiment architecture
Application acceptance fixtures use real PostgreSQL databases and HTTP hosts, standard credential hashing/protected tokens, controlled identities and an injectable token clock. They check persistence across host restarts, isolation, ownership, professional restrictions, period/category semantics and failures. Some tests seed directly into an owning DbContext to establish Given state; that is not production cross-service DB access. Test-specific replacement authentication verifies policy separation but is not the deployment mechanism.
Deployment acceptance builds/publishes a release, invokes the real offline installer/provisioner, creates isolated DBs/roles and launches five separate Production HTTPS processes at distinct loopback origins. It checks native config formats, secrets/certificate output, DB isolation, migrations, restart independence and representative workflows. SSH/SCP distribution and apt bootstrap commands use controlled doubles. Such tests cannot establish a real five-machine topology or native Windows/macOS service-manager operation. Evidence: [application fixture](../tests/Observation.AcceptanceTests/ObservationApiFixture.cs), [test token helper](../tests/Support/AuthenticatedTestClient.cs), [deployment fixture](../tests/Deployment.AcceptanceTests/DeploymentFixture.cs), [installation tests](../tests/Deployment.AcceptanceTests/InstallationTests.cs), [bootstrap tests](../tests/Deployment.AcceptanceTests/BootstrapTests.cs).
The optional [energy/JMeter tooling](../tools/energy-jmeter/README.md) runs outside the product processes. Generated JMX plans exercise synthetic API sessions, renew opaque tokens by login, and include Gaussian interaction delays. PerfMon ServerAgent host telemetry and Shelly plug HTTP power readings are collected live into JMeter, defaulting to one-second intervals. The runner separates warmup from the measured duration and reports request latency/throughput and CPU/RAM/power on aligned timelines. Idle sends no application requests. These agents/devices are experimental dependencies, not a sixth HealthApp service or a production monitoring/security guarantee. Private credentials and ignored raw experiment results were not inspected for this assignment.
## 12. Significant constraints and decisions
The architecture preserves independent process/persistence boundaries, Gateway-routed REST, controller APIs, external configuration and on-demand derived results. It deliberately uses pre-created accounts/assignments and synthetic data. No account administration, assignment-management UI, consent/emergency workflows, medication recommendations, professional edits or production identity-provider implementation is present; these are documented exclusions, not implicitly missing stories.
[Architecture decisions](architecture-decisions.md) distinguishes explicitly documented rationale from inferred consequences. [Requirements traceability](requirements-traceability.md) identifies implementation/verification limits without silently adding requirements. [Discrepancies](discrepancies.md) distinguishes superseded diagrams, current elaborations and unresolved evidence gaps. This documentation proposes no architectural or implementation changes.