feature: Observation Ingest, Synchronous Alert Detection, and Alert Lifecycle

This commit is contained in:
voltsrage
2026-06-16 21:05:06 +08:00
parent 882d4af3e6
commit de603df151
26 changed files with 1471 additions and 5 deletions
+6
View File
@@ -5,6 +5,8 @@ VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VigilCareClinicalAPI", "VigilCareClinicalAPI\VigilCareClinicalAPI.csproj", "{245ED672-EF15-4854-9C06-AB369139F7BE}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VigilCareClinicalAPI", "VigilCareClinicalAPI\VigilCareClinicalAPI.csproj", "{245ED672-EF15-4854-9C06-AB369139F7BE}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VigilCareClinicalAPI.Tests", "VigilCareClinicalAPI.Tests\VigilCareClinicalAPI.Tests.csproj", "{EECD0F7B-CF7E-4F42-826E-BE0E67AAC0A9}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -18,5 +20,9 @@ Global
{245ED672-EF15-4854-9C06-AB369139F7BE}.Debug|Any CPU.Build.0 = Debug|Any CPU {245ED672-EF15-4854-9C06-AB369139F7BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{245ED672-EF15-4854-9C06-AB369139F7BE}.Release|Any CPU.ActiveCfg = Release|Any CPU {245ED672-EF15-4854-9C06-AB369139F7BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{245ED672-EF15-4854-9C06-AB369139F7BE}.Release|Any CPU.Build.0 = Release|Any CPU {245ED672-EF15-4854-9C06-AB369139F7BE}.Release|Any CPU.Build.0 = Release|Any CPU
{EECD0F7B-CF7E-4F42-826E-BE0E67AAC0A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EECD0F7B-CF7E-4F42-826E-BE0E67AAC0A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EECD0F7B-CF7E-4F42-826E-BE0E67AAC0A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EECD0F7B-CF7E-4F42-826E-BE0E67AAC0A9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal
@@ -0,0 +1,94 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
[Collection("Integration")]
public class AlertLifecycleTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private readonly HttpClient _client;
private Guid _alertId;
public AlertLifecycleTests(ApiFixture fixture)
{
_fixture = fixture;
_client = fixture.CreateClient();
}
public async Task InitializeAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
var patient = new Patient
{
Id = Guid.NewGuid(), Mrn = "MRN-T002", FirstName = "Alert", LastName = "Test",
DateOfBirth = new DateOnly(1980, 6, 15), Gender = "M", CreatedAt = DateTimeOffset.UtcNow
};
var encounter = new Encounter
{
Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient,
Status = EncounterStatus.Active, Department = "General Medicine",
AttendingPhysician = "Dr. Test", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
var alert = new ClinicalAlert
{
Id = Guid.NewGuid(), EncounterId = encounter.Id, PatientId = patient.Id,
AlertType = AlertType.CriticalPotassiumMeqL, Severity = AlertSeverity.Critical,
Details = "Potassium 2.1 mEq/L is below critical low.", Status = AlertStatus.Open,
TriggeredAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
db.ClinicalAlerts.Add(alert);
await db.SaveChangesAsync();
_alertId = alert.Id;
}
public Task DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task AcknowledgeAlert_TransitionsToAcknowledged()
{
var resp = await _client.PostAsJsonAsync(
$"/api/v1/alerts/{_alertId}/acknowledge",
new { clinicianId = "DR-OSEI", note = "Reviewing now, ordering repeat labs." });
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await resp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("data").GetProperty("status").GetString()
.Should().Be("Acknowledged");
body.RootElement.GetProperty("data").GetProperty("acknowledgedBy").GetString()
.Should().Be("DR-OSEI");
}
[Fact]
public async Task ResolveWithoutAcknowledge_Returns409()
{
var resp = await _client.PostAsync($"/api/v1/alerts/{_alertId}/resolve", null);
resp.StatusCode.Should().Be(HttpStatusCode.Conflict);
var body = await resp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("error").GetProperty("code").GetString()
.Should().Be("ALERT_NOT_ACKNOWLEDGED");
}
[Fact]
public async Task AcknowledgeThenResolve_FullLifecycle()
{
await _client.PostAsJsonAsync(
$"/api/v1/alerts/{_alertId}/acknowledge",
new { clinicianId = "DR-PATEL", note = "Treated." });
var resolveResp = await _client.PostAsync(
$"/api/v1/alerts/{_alertId}/resolve", null);
resolveResp.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await resolveResp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("data").GetProperty("status").GetString()
.Should().Be("Resolved");
}
}
@@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
public class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
{
// Override configuration to point at a test database — never run tests against
// the development database; a botched rollback could corrupt seed data.
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureAppConfiguration((_, config) =>
{
config.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:DefaultConnection"] =
"Host=localhost;Port=5436;Database=vigilcare_test;Username=postgres;Password=password",
["Redis:ConnectionString"] = "localhost:6382,defaultDatabase=1,allowAdmin=true"
});
});
}
public async Task InitializeAsync()
{
// Apply migrations against the test database on first run
using var scope = Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
// Flush the test Redis database (db=1) to avoid cross-test cache pollution
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var server = redis.GetServer(redis.GetEndPoints().First());
await server.FlushDatabaseAsync(1);
}
public new async Task DisposeAsync()
{
await base.DisposeAsync();
}
}
@@ -0,0 +1,2 @@
[CollectionDefinition("Integration")]
public class IntegrationTestCollection : ICollectionFixture<ApiFixture>;
@@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
public static class DbResetHelper
{
// Truncate all data between tests — faster than dropping and re-creating
// the database, and preserves the schema (migrations do not re-run).
public static async Task ResetAsync(AppDbContext db)
{
await db.Database.ExecuteSqlRawAsync(@"
TRUNCATE TABLE reconciliation_alerts, outbox_events, orders,
clinical_alerts, observations, encounters,
alert_thresholds, patients
RESTART IDENTITY CASCADE;
");
}
}
@@ -0,0 +1,233 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
[Collection("Integration")]
public class ObservationIngestTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private readonly HttpClient _client;
private Guid _patientId;
private Guid _encounterId;
public ObservationIngestTests(ApiFixture fixture)
{
_fixture = fixture;
_client = fixture.CreateClient();
}
public async Task InitializeAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
// Seed one patient, one active encounter, and the four thresholds
var patient = new Patient
{
Id = Guid.NewGuid(), Mrn = "MRN-T001", FirstName = "Test", LastName = "Patient",
DateOfBirth = new DateOnly(1970, 1, 1), Gender = "F", CreatedAt = DateTimeOffset.UtcNow
};
var encounter = new Encounter
{
Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient,
Status = EncounterStatus.Active, Department = "ICU",
AttendingPhysician = "Dr. Test", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
db.AlertThresholds.AddRange(
new AlertThreshold { Id = Guid.NewGuid(), ObservationCode = "HEART_RATE",
DisplayName = "Heart Rate", Unit = "bpm",
CriticalLow = 30, WarningLow = 50, WarningHigh = 100, CriticalHigh = 150,
CreatedAt = DateTimeOffset.UtcNow },
new AlertThreshold { Id = Guid.NewGuid(), ObservationCode = "POTASSIUM_MEQ_L",
DisplayName = "Serum Potassium", Unit = "mEq/L",
CriticalLow = 2.5m, WarningLow = 3.5m, WarningHigh = 5.0m, CriticalHigh = 6.5m,
CreatedAt = DateTimeOffset.UtcNow }
);
await db.SaveChangesAsync();
// Pre-load thresholds into Redis (replicates what ThresholdCacheLoader does at startup)
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var cache = redis.GetDatabase(1);
await cache.StringSetAsync("threshold:HEART_RATE",
"""{"ObservationCode":"HEART_RATE","CriticalLow":30,"WarningLow":50,"WarningHigh":100,"CriticalHigh":150}""");
await cache.StringSetAsync("threshold:POTASSIUM_MEQ_L",
"""{"ObservationCode":"POTASSIUM_MEQ_L","CriticalLow":2.5,"WarningLow":3.5,"WarningHigh":5.0,"CriticalHigh":6.5}""");
_patientId = patient.Id;
_encounterId = encounter.Id;
}
public Task DisposeAsync() => Task.CompletedTask;
// Test 1: normal observation — no alert created
[Fact]
public async Task NormalObservation_NoAlert_Created()
{
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/observations",
new BatchIngestRequest(new List<IngestObservationRequest>
{
new("HEART_RATE", 78, "bpm", ObservationSource.Device, DateTimeOffset.UtcNow, null)
}));
resp.StatusCode.Should().Be(HttpStatusCode.Created);
var body = await resp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("data").GetProperty("alertGenerated").GetBoolean()
.Should().BeFalse();
body.RootElement.GetProperty("data").GetProperty("duplicate").GetBoolean()
.Should().BeFalse();
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alertCount = await db.ClinicalAlerts.CountAsync();
alertCount.Should().Be(0, "a normal value must not create an alert");
// Outbox event should still be written for the Kafka consumer (warning detection)
var outboxCount = await db.OutboxEvents.CountAsync();
outboxCount.Should().Be(1, "observation.recorded outbox event must be written for every observation");
var outboxTopic = await db.OutboxEvents.Select(e => e.Topic).FirstAsync();
outboxTopic.Should().Be("observation.recorded");
}
// Test 2: critical threshold breach — alert and outbox event in same transaction
[Fact]
public async Task CriticalBreach_AlertCreated_InSameTransaction()
{
// Potassium 2.1 mEq/L is below critical_low of 2.5 — immediately life-threatening
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/observations",
new BatchIngestRequest(new List<IngestObservationRequest>
{
new("POTASSIUM_MEQ_L", 2.1m, "mEq/L", ObservationSource.Lab, DateTimeOffset.UtcNow, "key-critical-001")
}));
resp.StatusCode.Should().Be(HttpStatusCode.Created);
var body = await resp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("data").GetProperty("alertGenerated").GetBoolean()
.Should().BeTrue();
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts.SingleAsync();
alert.Severity.Should().Be(AlertSeverity.Critical);
alert.Status.Should().Be(AlertStatus.Open);
alert.EncounterId.Should().Be(_encounterId);
alert.PatientId.Should().Be(_patientId);
// Both outbox events must exist: alert.generated AND observation.recorded
var topics = await db.OutboxEvents.Select(e => e.Topic).OrderBy(t => t).ToListAsync();
topics.Should().BeEquivalentTo(new[] { "alert.generated", "observation.recorded" });
}
// Test 3: warning threshold breach — no alert created; only observation.recorded outbox event
[Fact]
public async Task WarningBreach_NoAlertCreated_OnlyObservationOutboxEvent()
{
// Heart rate 104 bpm is above warning_high (100) but below critical_high (150)
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/observations",
new BatchIngestRequest(new List<IngestObservationRequest>
{
new("HEART_RATE", 104, "bpm", ObservationSource.Device, DateTimeOffset.UtcNow, null)
}));
resp.StatusCode.Should().Be(HttpStatusCode.Created);
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alertCount = await db.ClinicalAlerts.CountAsync();
alertCount.Should().Be(0, "warning detection is deferred to the Kafka consumer in Phase 3");
var topics = await db.OutboxEvents.Select(e => e.Topic).ToListAsync();
topics.Should().ContainSingle().Which.Should().Be("observation.recorded");
}
// Test 4: duplicate idempotency key — returns 201 with original observation, no duplicate
[Fact]
public async Task DuplicateIdempotencyKey_Returns201_NoDuplicateRow()
{
var payload = new BatchIngestRequest(new List<IngestObservationRequest>
{
new("HEART_RATE", 78, "bpm", ObservationSource.Device, DateTimeOffset.UtcNow, "device-key-abc123")
});
var resp1 = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/observations", payload);
var resp2 = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/observations", payload);
resp1.StatusCode.Should().Be(HttpStatusCode.Created);
resp2.StatusCode.Should().Be(HttpStatusCode.Created);
var body2 = await resp2.Content.ReadFromJsonAsync<JsonDocument>();
body2!.RootElement.GetProperty("data").GetProperty("duplicate").GetBoolean()
.Should().BeTrue("the second call must be identified as a duplicate");
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var count = await db.Observations.CountAsync();
count.Should().Be(1, "only one observation row must exist despite two identical requests");
}
// Test 5: discharged encounter — 409 returned, no observation written
[Fact]
public async Task DischargedEncounter_Returns409_NoObservationWritten()
{
// Discharge the encounter
var patchResp = await _client.PatchAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/status",
new { status = "Discharged" });
patchResp.StatusCode.Should().Be(HttpStatusCode.OK);
// Attempt to ingest against a discharged encounter
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/observations",
new BatchIngestRequest(new List<IngestObservationRequest>
{
new("HEART_RATE", 78, "bpm", ObservationSource.Device, DateTimeOffset.UtcNow, null)
}));
resp.StatusCode.Should().Be(HttpStatusCode.Conflict);
var body = await resp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("error").GetProperty("code").GetString()
.Should().Be("ENCOUNTER_NOT_ACTIVE");
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var count = await db.Observations.CountAsync();
count.Should().Be(0, "no observation must be written when encounter is not active");
}
// Test 6: plausibility violation — 422 returned, no rows written
[Fact]
public async Task ImplausibleValue_Returns422_NoRowsWritten()
{
// Heart rate of 350 bpm: above plausibility ceiling of 300
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{_encounterId}/observations",
new BatchIngestRequest(new List<IngestObservationRequest>
{
new("HEART_RATE", 350, "bpm", ObservationSource.Device, DateTimeOffset.UtcNow, null)
}));
resp.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
var body = await resp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("error").GetProperty("code").GetString()
.Should().Be("OBSERVATION_OUT_OF_PLAUSIBLE_RANGE");
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
(await db.Observations.CountAsync()).Should().Be(0);
(await db.OutboxEvents.CountAsync()).Should().Be(0);
}
}
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.4" />
<PackageReference Include="StackExchange.Redis" Version="3.0.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VigilCareClinicalAPI\VigilCareClinicalAPI.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1 @@
public record CursorPage<T>(List<T> Items, string? NextCursor, bool HasMore);
@@ -0,0 +1,156 @@
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// Clinical alert listing, acknowledgment, and resolution.
/// </summary>
[ApiController]
[Produces("application/json")]
public class AlertsController : ControllerBase
{
private readonly IAlertService _alerts;
public AlertsController(IAlertService alerts) => _alerts = alerts;
/// <summary>
/// Lists alerts for a single encounter with optional status filter.
/// </summary>
/// <param name="encounterId">Encounter id.</param>
/// <param name="status">Optional status filter (DB literal, e.g. OPEN).</param>
/// <param name="page">Page number (1-based).</param>
/// <param name="pageSize">Results per page.</param>
/// <returns>A paginated list of alerts for the encounter.</returns>
[HttpGet("api/v1/encounters/{encounterId:guid}/alerts")]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListByEncounter(
Guid encounterId,
[FromQuery] string? status,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
{
AlertStatus? parsedStatus = null;
if (!string.IsNullOrEmpty(status))
{
try
{
parsedStatus = AlertStatusExtensions.FromDbString(status);
}
catch (ArgumentOutOfRangeException)
{
return BadRequest(ApiResponse<object>.Fail(400, "Invalid status filter.", "INVALID_STATUS"));
}
}
var result = await _alerts.ListByEncounterAsync(encounterId, parsedStatus, page, pageSize);
return Ok(ApiResponse<object>.Ok(new
{
items = result.Items,
page = result.Page,
pageSize = result.PageSize,
totalCount = result.TotalCount,
totalPages = result.TotalPages
}));
}
/// <summary>
/// Lists alerts across all encounters with optional status, severity, and department filters.
/// </summary>
/// <param name="status">Optional status filter (DB literal, e.g. OPEN).</param>
/// <param name="severity">Optional severity filter (DB literal, e.g. CRITICAL).</param>
/// <param name="department">Optional department filter.</param>
/// <param name="page">Page number (1-based).</param>
/// <param name="pageSize">Results per page.</param>
/// <returns>A paginated list of alerts.</returns>
[HttpGet("api/v1/alerts")]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListGlobal(
[FromQuery] string? status,
[FromQuery] string? severity,
[FromQuery] string? department,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
{
AlertStatus? parsedStatus = null;
if (!string.IsNullOrEmpty(status))
{
try
{
parsedStatus = AlertStatusExtensions.FromDbString(status);
}
catch (ArgumentOutOfRangeException)
{
return BadRequest(ApiResponse<object>.Fail(400, "Invalid status filter.", "INVALID_STATUS"));
}
}
AlertSeverity? parsedSeverity = null;
if (!string.IsNullOrEmpty(severity))
{
try
{
parsedSeverity = AlertSeverityExtensions.FromDbString(severity);
}
catch (ArgumentOutOfRangeException)
{
return BadRequest(ApiResponse<object>.Fail(400, "Invalid severity filter.", "INVALID_SEVERITY"));
}
}
var result = await _alerts.ListGlobalAsync(parsedStatus, parsedSeverity, department, page, pageSize);
return Ok(ApiResponse<object>.Ok(new
{
items = result.Items,
page = result.Page,
pageSize = result.PageSize,
totalCount = result.TotalCount,
totalPages = result.TotalPages
}));
}
/// <summary>
/// Gets a single alert by id, including its encounter.
/// </summary>
/// <param name="id">Alert id.</param>
/// <returns>The alert record.</returns>
[HttpGet("api/v1/alerts/{id:guid}")]
[ProducesResponseType(typeof(ApiResponse<ClinicalAlert>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Get(Guid id)
{
var alert = await _alerts.GetByIdAsync(id);
return Ok(ApiResponse<ClinicalAlert>.Ok(alert));
}
/// <summary>
/// Acknowledges an open or escalated alert and emits an outbox event for downstream consumers.
/// </summary>
/// <param name="id">Alert id.</param>
/// <param name="req">Clinician id and optional note.</param>
/// <returns>The updated alert.</returns>
[HttpPost("api/v1/alerts/{id:guid}/acknowledge")]
[ProducesResponseType(typeof(ApiResponse<ClinicalAlert>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
public async Task<IActionResult> Acknowledge(Guid id, [FromBody] AcknowledgeAlertRequest req)
{
var alert = await _alerts.AcknowledgeAsync(id, req);
return Ok(ApiResponse<ClinicalAlert>.Ok(alert));
}
/// <summary>
/// Resolves an acknowledged alert.
/// </summary>
/// <param name="id">Alert id.</param>
/// <returns>The updated alert.</returns>
[HttpPost("api/v1/alerts/{id:guid}/resolve")]
[ProducesResponseType(typeof(ApiResponse<ClinicalAlert>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
public async Task<IActionResult> Resolve(Guid id)
{
var alert = await _alerts.ResolveAsync(id);
return Ok(ApiResponse<ClinicalAlert>.Ok(alert));
}
}
@@ -0,0 +1,87 @@
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// Observation ingest and cursor-paginated history for an encounter.
/// </summary>
[ApiController]
[Route("api/v1/encounters/{encounterId:guid}/observations")]
[Produces("application/json")]
public class ObservationsController : ControllerBase
{
private readonly IObservationService _ingest;
private readonly IObservationQueryService _query;
public ObservationsController(IObservationService ingest, IObservationQueryService query)
{
_ingest = ingest;
_query = query;
}
/// <summary>
/// Ingests one to ten observations for an encounter in a single request.
/// </summary>
/// <param name="encounterId">Encounter id.</param>
/// <param name="req">Batch of observations to record.</param>
/// <returns>Per-observation ingest results, including any generated alerts.</returns>
[HttpPost]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Ingest(Guid encounterId, [FromBody] BatchIngestRequest req)
{
if (req.Observations.Count == 0)
return BadRequest(ApiResponse<object>.Fail(400, "At least one observation is required.", "EMPTY_BATCH"));
if (req.Observations.Count > 10)
return BadRequest(ApiResponse<object>.Fail(400,
"Batch size cannot exceed 10 observations.", "BATCH_TOO_LARGE"));
var results = new List<object>();
foreach (var obs in req.Observations)
{
var result = await _ingest.IngestAsync(encounterId, obs);
results.Add(new
{
observation = result.Observation,
alertGenerated = result.AlertCreated is not null,
alertId = result.AlertCreated?.Id,
duplicate = result.IsDuplicate
});
}
return StatusCode(201, ApiResponse<object>.Created(
req.Observations.Count == 1 ? (object)results[0] : results));
}
/// <summary>
/// Returns cursor-paginated observation history for an encounter.
/// </summary>
/// <param name="encounterId">Encounter id.</param>
/// <param name="code">Optional observation code filter.</param>
/// <param name="from">Optional start of recorded-at range.</param>
/// <param name="to">Optional end of recorded-at range.</param>
/// <param name="limit">Maximum items per page.</param>
/// <param name="cursor">Opaque cursor from a previous page.</param>
/// <returns>A page of observations with an optional next cursor.</returns>
[HttpGet]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
public async Task<IActionResult> History(
Guid encounterId,
[FromQuery] string? code,
[FromQuery] DateTimeOffset? from,
[FromQuery] DateTimeOffset? to,
[FromQuery] int limit = 50,
[FromQuery] string? cursor = null)
{
var page = await _query.GetHistoryAsync(encounterId, code, from, to, limit, cursor);
return Ok(ApiResponse<object>.Ok(new
{
items = page.Items,
nextCursor = page.NextCursor,
hasMore = page.HasMore
}));
}
}
@@ -0,0 +1 @@
public record AcknowledgeAlertRequest(string ClinicianId, string? Note);
@@ -0,0 +1 @@
public record BatchIngestRequest(List<IngestObservationRequest> Observations);
@@ -0,0 +1,8 @@
public record IngestObservationRequest(
string ObservationCode,
decimal Value,
string Unit,
ObservationSource Source,
DateTimeOffset RecordedAt,
string? IdempotencyKey
);
@@ -0,0 +1,8 @@
public record IngestResult(Observation Observation, ClinicalAlert? AlertCreated, bool IsDuplicate = false)
{
public static IngestResult Created(Observation obs, ClinicalAlert? alert) =>
new(obs, alert, false);
public static IngestResult Duplicate(Observation obs) =>
new(obs, null, true);
}
@@ -0,0 +1,25 @@
using System.Text;
using System.Text.Json;
public record ObservationCursor(DateTimeOffset RecordedAt, Guid Id)
{
public string Encode()
{
var json = JsonSerializer.Serialize(this);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
}
public static ObservationCursor? Decode(string? encoded)
{
if (string.IsNullOrEmpty(encoded)) return null;
try
{
var json = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
return JsonSerializer.Deserialize<ObservationCursor>(json);
}
catch
{
return null;
}
}
}
@@ -0,0 +1,6 @@
public record ThresholdCacheEntry(
string ObservationCode,
decimal? CriticalLow,
decimal? WarningLow,
decimal? WarningHigh,
decimal? CriticalHigh);
+18 -4
View File
@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Serilog; using Serilog;
using StackExchange.Redis; using StackExchange.Redis;
using System.Text.Json.Serialization;
Log.Logger = new LoggerConfiguration() Log.Logger = new LoggerConfiguration()
.WriteTo.Console() .WriteTo.Console()
@@ -18,23 +19,33 @@ try
builder.Services.AddDbContext<AppDbContext>(opts => builder.Services.AddDbContext<AppDbContext>(opts =>
opts.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))); opts.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddSingleton<IConnectionMultiplexer>( builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
ConnectionMultiplexer.Connect(builder.Configuration["Redis:ConnectionString"]!)); ConnectionMultiplexer.Connect(sp.GetRequiredService<IConfiguration>()["Redis:ConnectionString"]!));
builder.Services.AddScoped<IPatientService, PatientService>(); builder.Services.AddScoped<IPatientService, PatientService>();
builder.Services.AddScoped<IEncounterService, EncounterService>(); builder.Services.AddScoped<IEncounterService, EncounterService>();
builder.Services.AddScoped<IAlertThresholdService, AlertThresholdService>(); builder.Services.AddScoped<IAlertThresholdService, AlertThresholdService>();
builder.Services.AddScoped<IObservationService, ObservationService>();
builder.Services.AddScoped<IObservationQueryService, ObservationQueryService>();
builder.Services.AddScoped<IAlertService, AlertService>();
builder.Services.AddHostedService<ThresholdCacheLoader>(); builder.Services.AddHostedService<ThresholdCacheLoader>();
builder.Services.AddControllers(); builder.Services.AddControllers()
.AddJsonOptions(opts =>
{
opts.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
opts.JsonSerializerOptions.Converters.Add(new ObservationSourceJsonConverter());
});
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
var app = builder.Build(); var app = builder.Build();
using (var scope = app.Services.CreateScope()) if (!app.Environment.IsEnvironment("Testing"))
{ {
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>(); var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await DataSeeder.SeedAsync(db, redis); await DataSeeder.SeedAsync(db, redis);
@@ -71,8 +82,11 @@ catch (HostAbortedException)
catch (Exception ex) catch (Exception ex)
{ {
Log.Fatal(ex, "Application failed to start."); Log.Fatal(ex, "Application failed to start.");
throw;
} }
finally finally
{ {
Log.CloseAndFlush(); Log.CloseAndFlush();
} }
public partial class Program { }
@@ -0,0 +1,123 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public class AlertService : IAlertService
{
private readonly AppDbContext _db;
public AlertService(AppDbContext db) => _db = db;
public async Task<PagedResult<ClinicalAlert>> ListByEncounterAsync(
Guid encounterId, AlertStatus? status, int page, int pageSize)
{
var query = _db.ClinicalAlerts
.AsNoTracking()
.Where(a => a.EncounterId == encounterId);
if (status.HasValue)
query = query.Where(a => a.Status == status.Value);
var total = await query.CountAsync();
var alerts = await query
.OrderByDescending(a => a.TriggeredAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return new PagedResult<ClinicalAlert>(alerts, page, pageSize, total);
}
public async Task<PagedResult<ClinicalAlert>> ListGlobalAsync(
AlertStatus? status, AlertSeverity? severity, string? department, int page, int pageSize)
{
var query = _db.ClinicalAlerts
.AsNoTracking()
.Include(a => a.Encounter)
.AsQueryable();
if (status.HasValue)
query = query.Where(a => a.Status == status.Value);
if (severity.HasValue)
query = query.Where(a => a.Severity == severity.Value);
if (!string.IsNullOrEmpty(department))
query = query.Where(a => a.Encounter.Department == department);
var total = await query.CountAsync();
var alerts = await query
.OrderByDescending(a => a.TriggeredAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return new PagedResult<ClinicalAlert>(alerts, page, pageSize, total);
}
public async Task<ClinicalAlert> GetByIdAsync(Guid id)
{
var alert = await _db.ClinicalAlerts
.AsNoTracking()
.Include(a => a.Encounter)
.FirstOrDefaultAsync(a => a.Id == id);
if (alert is null)
throw new NotFoundException("Alert not found.", "ALERT_NOT_FOUND");
return alert;
}
public async Task<ClinicalAlert> AcknowledgeAsync(Guid id, AcknowledgeAlertRequest req)
{
var alert = await _db.ClinicalAlerts.FindAsync(id);
if (alert is null)
throw new NotFoundException("Alert not found.", "ALERT_NOT_FOUND");
if (alert.Status != AlertStatus.Open && alert.Status != AlertStatus.Escalated)
throw new ConflictException(
$"Alert cannot be acknowledged from status '{alert.Status}'.",
"ALERT_NOT_ACKNOWLEDGEABLE");
alert.Status = AlertStatus.Acknowledged;
alert.AcknowledgedAt = DateTimeOffset.UtcNow;
alert.AcknowledgedBy = req.ClinicianId;
// Write an outbox event so the Kafka consumer (Phase 6) can cancel the
// pending RabbitMQ escalation timer when it sees this acknowledgment.
_db.OutboxEvents.Add(new OutboxEvent
{
Id = Guid.NewGuid(),
Topic = "alert.acknowledged",
Payload = JsonSerializer.Serialize(new
{
alertId = alert.Id,
encounterId = alert.EncounterId,
acknowledgedBy = req.ClinicianId,
acknowledgedAt = alert.AcknowledgedAt,
note = req.Note
}),
CreatedAt = DateTimeOffset.UtcNow
});
await _db.SaveChangesAsync();
return alert;
}
public async Task<ClinicalAlert> ResolveAsync(Guid id)
{
var alert = await _db.ClinicalAlerts.FindAsync(id);
if (alert is null)
throw new NotFoundException("Alert not found.", "ALERT_NOT_FOUND");
if (alert.Status != AlertStatus.Acknowledged)
throw new ConflictException(
"Alert must be acknowledged before it can be resolved.",
"ALERT_NOT_ACKNOWLEDGED");
alert.Status = AlertStatus.Resolved;
alert.ResolvedAt = DateTimeOffset.UtcNow;
await _db.SaveChangesAsync();
return alert;
}
}
@@ -0,0 +1,14 @@
public interface IAlertService
{
Task<PagedResult<ClinicalAlert>> ListByEncounterAsync(
Guid encounterId, AlertStatus? status, int page, int pageSize);
Task<PagedResult<ClinicalAlert>> ListGlobalAsync(
AlertStatus? status, AlertSeverity? severity, string? department, int page, int pageSize);
Task<ClinicalAlert> GetByIdAsync(Guid id);
Task<ClinicalAlert> AcknowledgeAsync(Guid id, AcknowledgeAlertRequest req);
Task<ClinicalAlert> ResolveAsync(Guid id);
}
@@ -0,0 +1,10 @@
public interface IObservationQueryService
{
Task<CursorPage<Observation>> GetHistoryAsync(
Guid encounterId,
string? code,
DateTimeOffset? from,
DateTimeOffset? to,
int limit,
string? cursorToken);
}
@@ -0,0 +1,4 @@
public interface IObservationService
{
Task<IngestResult> IngestAsync(Guid encounterId, IngestObservationRequest req);
}
@@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore;
public class ObservationQueryService : IObservationQueryService
{
private readonly AppDbContext _db;
public ObservationQueryService(AppDbContext db) => _db = db;
public async Task<CursorPage<Observation>> GetHistoryAsync(
Guid encounterId,
string? code,
DateTimeOffset? from,
DateTimeOffset? to,
int limit,
string? cursorToken)
{
limit = Math.Clamp(limit, 1, 100);
var cursor = ObservationCursor.Decode(cursorToken);
var query = _db.Observations
.AsNoTracking()
.Where(o => o.EncounterId == encounterId);
if (!string.IsNullOrEmpty(code))
query = query.Where(o => o.ObservationCode == code);
if (from.HasValue)
query = query.Where(o => o.RecordedAt >= from.Value);
if (to.HasValue)
query = query.Where(o => o.RecordedAt <= to.Value);
if (cursor is not null)
{
// Keyset condition for ORDER BY recorded_at DESC, id DESC:
// next page starts just below the cursor position
var cursorTime = cursor.RecordedAt;
var cursorId = cursor.Id;
query = query.Where(o =>
o.RecordedAt < cursorTime ||
(o.RecordedAt == cursorTime && o.Id.CompareTo(cursorId) < 0));
}
var items = await query
.OrderByDescending(o => o.RecordedAt)
.ThenByDescending(o => o.Id)
.Take(limit + 1) // fetch one extra to know if there is a next page
.ToListAsync();
var hasMore = items.Count > limit;
if (hasMore) items.RemoveAt(limit);
var nextCursor = hasMore
? new ObservationCursor(items[^1].RecordedAt, items[^1].Id).Encode()
: null;
return new CursorPage<Observation>(items, nextCursor, hasMore);
}
}
@@ -0,0 +1,215 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using StackExchange.Redis;
public class ObservationService : IObservationService
{
private readonly AppDbContext _db;
private readonly IConnectionMultiplexer _redis;
private readonly ILogger<ObservationService> _logger;
public ObservationService(
AppDbContext db,
IConnectionMultiplexer redis,
ILogger<ObservationService> logger)
{
_db = db;
_redis = redis;
_logger = logger;
}
public async Task<IngestResult> IngestAsync(Guid encounterId, IngestObservationRequest req)
{
// Step 1 — encounter must be active
var encounter = await _db.Encounters
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == encounterId);
if (encounter is null)
throw new NotFoundException("Encounter not found.", "ENCOUNTER_NOT_FOUND");
if (encounter.Status != EncounterStatus.Active)
throw new ConflictException(
$"Cannot record observations for an encounter with status '{encounter.Status}'.",
"ENCOUNTER_NOT_ACTIVE");
// Step 2 — idempotency check before entering the transaction
// The unique partial index is the database safety net for concurrent retries.
// The pre-check here avoids the exception-and-rollback path for the common retry case.
if (!string.IsNullOrEmpty(req.IdempotencyKey))
{
var existing = await _db.Observations
.AsNoTracking()
.FirstOrDefaultAsync(o => o.IdempotencyKey == req.IdempotencyKey);
if (existing is not null)
{
_logger.LogInformation(
"Duplicate idempotency key {Key} for encounter {EncounterId} — returning original",
req.IdempotencyKey, encounterId);
return IngestResult.Duplicate(existing);
}
}
// Step 3 — plausibility check
if (!PlausibilityValidator.IsPlausible(req.ObservationCode, req.Value, out var reason))
throw new ValidationException(reason!, "OBSERVATION_OUT_OF_PLAUSIBLE_RANGE");
// Steps 48 are one atomic transaction
await using var tx = await _db.Database.BeginTransactionAsync();
try
{
// Step 4 — insert observation
var observation = new Observation
{
Id = Guid.NewGuid(),
EncounterId = encounterId,
ObservationCode = req.ObservationCode,
Value = req.Value,
Unit = req.Unit,
Source = req.Source,
IdempotencyKey = req.IdempotencyKey,
RecordedAt = req.RecordedAt,
CreatedAt = DateTimeOffset.UtcNow
};
_db.Observations.Add(observation);
// Step 5 — load threshold from Redis; fall back to PostgreSQL on miss
var threshold = await LoadThresholdAsync(req.ObservationCode);
if (threshold is null)
throw new ValidationException(
$"No alert threshold is configured for observation code '{req.ObservationCode}'. " +
"Register a threshold before recording observations for this code.",
"UNKNOWN_OBSERVATION_CODE");
ClinicalAlert? alert = null;
// Step 6 — critical threshold detection (synchronous)
// WARNING detection is intentionally deferred to the Kafka consumer.
// A critical potassium of 2.1 mEq/L is immediately life-threatening — the alert
// must exist before this API call returns. A warning heart rate of 95 bpm warrants
// attention but not an emergency page; the additional Kafka latency is clinically safe.
if (IsCriticalBreach(req.Value, threshold))
{
alert = new ClinicalAlert
{
Id = Guid.NewGuid(),
EncounterId = encounterId,
PatientId = encounter.PatientId,
ObservationId = observation.Id,
AlertType = AlertTypeExtensions.CriticalFor(req.ObservationCode),
Severity = AlertSeverity.Critical,
Details = BuildCriticalDetails(req, threshold),
Status = AlertStatus.Open,
TriggeredAt = DateTimeOffset.UtcNow
};
_db.ClinicalAlerts.Add(alert);
// Step 6b — outbox event for the alert (relay picks this up in Phase 3)
_db.OutboxEvents.Add(BuildOutboxEvent("alert.generated", new
{
alertId = alert.Id,
encounterId,
patientId = encounter.PatientId,
alertType = alert.AlertType.ToDbString(),
severity = alert.Severity.ToDbString(),
triggeredAt = alert.TriggeredAt,
partitionKey = encounterId.ToString()
}));
}
// Step 7 — outbox event for the observation (always; Kafka consumer handles warnings)
_db.OutboxEvents.Add(BuildOutboxEvent("observation.recorded", new
{
observationId = observation.Id,
encounterId,
patientId = encounter.PatientId,
observationCode = req.ObservationCode,
value = req.Value,
unit = req.Unit,
source = req.Source.ToDbString(),
recordedAt = req.RecordedAt,
partitionKey = encounterId.ToString()
}));
// Step 8 — COMMIT
await _db.SaveChangesAsync();
await tx.CommitAsync();
_logger.LogInformation(
"Observation {ObservationId} ingested for encounter {EncounterId}. AlertCreated={AlertCreated}",
observation.Id, encounterId, alert is not null);
return IngestResult.Created(observation, alert);
}
catch (DbUpdateException ex) when (IsUniqueViolation(ex))
{
// Race condition: two concurrent retries both passed the pre-check above.
// The unique partial index caught it. Roll back and return the existing row.
await tx.RollbackAsync();
var existing = await _db.Observations
.AsNoTracking()
.FirstOrDefaultAsync(o => o.IdempotencyKey == req.IdempotencyKey);
if (existing is not null)
return IngestResult.Duplicate(existing);
throw new ConflictException("Concurrent duplicate submission.", "CONCURRENT_DUPLICATE");
}
catch
{
await tx.RollbackAsync();
throw;
}
}
private async Task<ThresholdCacheEntry?> LoadThresholdAsync(string observationCode)
{
var cache = _redis.GetDatabase();
var cacheKey = $"threshold:{observationCode}";
var cached = await cache.StringGetAsync(cacheKey);
if (cached.HasValue)
return JsonSerializer.Deserialize<ThresholdCacheEntry>(cached!);
// Cache miss — read from PostgreSQL and write back
var threshold = await _db.AlertThresholds
.AsNoTracking()
.FirstOrDefaultAsync(t => t.ObservationCode == observationCode);
if (threshold is null) return null;
var entry = new ThresholdCacheEntry(
threshold.ObservationCode,
threshold.CriticalLow,
threshold.WarningLow,
threshold.WarningHigh,
threshold.CriticalHigh);
await cache.StringSetAsync(cacheKey, JsonSerializer.Serialize(entry));
_logger.LogDebug("Cache miss for threshold {Code} — loaded from PostgreSQL", observationCode);
return entry;
}
private static bool IsCriticalBreach(decimal value, ThresholdCacheEntry t) =>
(t.CriticalLow.HasValue && value < t.CriticalLow.Value) ||
(t.CriticalHigh.HasValue && value > t.CriticalHigh.Value);
private static string BuildCriticalDetails(IngestObservationRequest req, ThresholdCacheEntry t)
{
if (t.CriticalLow.HasValue && req.Value < t.CriticalLow.Value)
return $"{req.ObservationCode} value {req.Value} {req.Unit} is below critical low of {t.CriticalLow} {req.Unit}.";
return $"{req.ObservationCode} value {req.Value} {req.Unit} is above critical high of {t.CriticalHigh} {req.Unit}.";
}
private static OutboxEvent BuildOutboxEvent(string topic, object payload) => new()
{
Id = Guid.NewGuid(),
Topic = topic,
Payload = JsonSerializer.Serialize(payload),
CreatedAt = DateTimeOffset.UtcNow
};
private static bool IsUniqueViolation(DbUpdateException ex) =>
ex.InnerException is Npgsql.PostgresException pg && pg.SqlState == "23505";
}
@@ -0,0 +1,35 @@
public static class PlausibilityValidator
{
// Plausible ranges define the outer boundary of physically possible values.
// These are NOT clinical thresholds — they catch device malfunctions and typos.
// A heart rate of 300 is clinically impossible; 150 is critical but possible.
private static readonly Dictionary<string, (decimal Min, decimal Max)> _ranges = new()
{
["HEART_RATE"] = (1, 300),
["TEMP_C"] = (20, 50),
["POTASSIUM_MEQ_L"] = (0.1m, 15),
["SPO2"] = (50, 100),
["RESP_RATE"] = (1, 80),
["WBC_K_UL"] = (0.1m, 500),
["GLUCOSE_MG_DL"] = (10, 1500),
};
public static bool IsPlausible(string observationCode, decimal value, out string? reason)
{
if (!_ranges.TryGetValue(observationCode, out var range))
{
// Unknown codes pass plausibility — threshold lookup will validate the code
reason = null;
return true;
}
if (value < range.Min || value > range.Max)
{
reason = $"Value {value} is outside the plausible range [{range.Min}{range.Max}] for {observationCode}.";
return false;
}
reason = null;
return true;
}
}
@@ -0,0 +1,14 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Warning",
"Override": {
"Microsoft.AspNetCore": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" }
]
}
}
+260
View File
@@ -0,0 +1,260 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMPOSE_FILE="${COMPOSE_FILE:-${SCRIPT_DIR}/../docker-compose.yml}"
BASE_URL="${BASE_URL:-http://localhost:5270}"
REDIS_PORT="${REDIS_PORT:-6382}"
REDIS_KEY="${REDIS_KEY:-threshold:HEART_RATE}"
RECORDED_AT="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
TMP_FILES=()
cleanup() {
local f
for f in "${TMP_FILES[@]}"; do
rm -f "${f}" "${f}.status"
done
}
trap cleanup EXIT
if ! command -v curl >/dev/null 2>&1; then
echo "Missing dependency: curl"
exit 1
fi
if ! command -v jq >/dev/null 2>&1; then
echo "Missing dependency: jq"
exit 1
fi
redis_cmd() {
if command -v redis-cli >/dev/null 2>&1; then
redis-cli -p "${REDIS_PORT}" "$@"
elif command -v docker >/dev/null 2>&1 && [[ -f "${COMPOSE_FILE}" ]]; then
docker compose -f "${COMPOSE_FILE}" exec -T redis redis-cli "$@"
else
echo "Missing dependency: redis-cli (or docker compose with redis service)"
exit 1
fi
}
request() {
local method="$1"
local url="$2"
local body="${3:-}"
local tmp_body
tmp_body="$(mktemp)"
TMP_FILES+=("${tmp_body}")
local status
if [[ -n "${body}" ]]; then
status="$(curl -sS -o "${tmp_body}" -w "%{http_code}" -X "${method}" "${url}" \
-H "Content-Type: application/json" -d "${body}")"
else
status="$(curl -sS -o "${tmp_body}" -w "%{http_code}" -X "${method}" "${url}")"
fi
echo "${status}" > "${tmp_body}.status"
echo "${tmp_body}"
}
assert_status() {
local expected="$1"
local body_file="$2"
local status
status="$(cat "${body_file}.status")"
if [[ "${status}" != "${expected}" ]]; then
echo "Expected HTTP ${expected}, got ${status}"
echo "Response body:"
cat "${body_file}"
echo
return 1
fi
}
assert_json() {
local body_file="$1"
local jq_expr="$2"
local expected="$3"
local actual
actual="$(jq -r "${jq_expr}" "${body_file}")"
if [[ "${actual}" != "${expected}" ]]; then
echo "Expected ${jq_expr} = ${expected}, got ${actual}"
echo "Response body:"
cat "${body_file}"
echo
return 1
fi
}
TOTAL_STEPS=16
echo "Running API + Redis verification against ${BASE_URL}"
echo "Recorded-at timestamp: ${RECORDED_AT}"
echo ""
echo "[0/${TOTAL_STEPS}] Preflight — API reachable"
preflight_status="$(curl -sS -o /dev/null -w "%{http_code}" "${BASE_URL}/api/v1/alert-thresholds" || true)"
if [[ "${preflight_status}" != "200" ]]; then
echo "API not reachable at ${BASE_URL} (HTTP ${preflight_status})."
echo "Start the API with: dotnet run --project VigilCareClinicalAPI"
exit 1
fi
echo "OK: API is up"
echo ""
echo "[1/${TOTAL_STEPS}] Listing thresholds"
resp="$(request GET "${BASE_URL}/api/v1/alert-thresholds")"
assert_status "200" "${resp}"
threshold_id="$(jq -r '.data[] | select(.observationCode=="HEART_RATE") | .id' "${resp}" | head -n 1)"
if [[ -z "${threshold_id}" || "${threshold_id}" == "null" ]]; then
echo "Could not find HEART_RATE threshold id."
exit 1
fi
echo "OK: HEART_RATE threshold id = ${threshold_id}"
echo ""
echo "[2/${TOTAL_STEPS}] Registering patient"
patient_payload='{"firstName":"Test","lastName":"Runner","dateOfBirth":"1988-01-10","gender":"F"}'
resp="$(request POST "${BASE_URL}/api/v1/patients" "${patient_payload}")"
assert_status "201" "${resp}"
patient_id="$(jq -r '.data.id' "${resp}")"
if [[ -z "${patient_id}" || "${patient_id}" == "null" ]]; then
echo "Could not parse patient id."
exit 1
fi
echo "OK: patient id = ${patient_id}"
echo ""
echo "[3/${TOTAL_STEPS}] Opening encounter"
enc_payload='{"encounterType":"Inpatient","department":"ICU","attendingPhysician":"Dr. Script"}'
resp="$(request POST "${BASE_URL}/api/v1/patients/${patient_id}/encounters" "${enc_payload}")"
assert_status "201" "${resp}"
encounter_id="$(jq -r '.data.id' "${resp}")"
if [[ -z "${encounter_id}" || "${encounter_id}" == "null" ]]; then
echo "Could not parse encounter id."
exit 1
fi
echo "OK: encounter id = ${encounter_id}"
echo ""
echo "[4/${TOTAL_STEPS}] Verifying illegal status transition returns 409"
transition_payload='{"status":"Scheduled"}'
resp="$(request PATCH "${BASE_URL}/api/v1/encounters/${encounter_id}/status" "${transition_payload}")"
assert_status "409" "${resp}"
error_code="$(jq -r '.error.code' "${resp}")"
echo "OK: illegal transition blocked (${error_code})"
echo ""
echo "[5/${TOTAL_STEPS}] Updating HEART_RATE threshold"
update_payload='{"observationCode":"HEART_RATE","displayName":"Heart Rate","unit":"bpm","criticalLow":30,"warningLow":50,"warningHigh":110,"criticalHigh":160}'
resp="$(request PUT "${BASE_URL}/api/v1/alert-thresholds/${threshold_id}" "${update_payload}")"
assert_status "200" "${resp}"
echo "OK: threshold update accepted"
echo ""
echo "[6/${TOTAL_STEPS}] Verifying Redis invalidation"
redis_value="$(redis_cmd GET "${REDIS_KEY}" | tr -d '\r')"
if [[ "${redis_value}" != "(nil)" && -n "${redis_value}" ]]; then
echo "Expected Redis key ${REDIS_KEY} to be invalidated, but found value."
echo "Value: ${redis_value}"
exit 1
fi
echo "OK: Redis key invalidated (${REDIS_KEY})"
echo ""
echo "[7/${TOTAL_STEPS}] Listing patient"
resp="$(request GET "${BASE_URL}/api/v1/patients/${patient_id}")"
assert_status "200" "${resp}"
echo "OK: patient lookup succeeds"
echo ""
echo "[8/${TOTAL_STEPS}] Ingesting normal observation (no alert)"
normal_obs_payload="$(jq -nc \
--arg recordedAt "${RECORDED_AT}" \
'{observations:[{observationCode:"HEART_RATE",value:78,unit:"bpm",source:"DEVICE",recordedAt:$recordedAt}]}')"
resp="$(request POST "${BASE_URL}/api/v1/encounters/${encounter_id}/observations" "${normal_obs_payload}")"
assert_status "201" "${resp}"
assert_json "${resp}" '.data.alertGenerated' 'false'
echo "OK: normal observation ingested without alert"
echo ""
echo "[9/${TOTAL_STEPS}] Ingesting critical potassium (alert expected)"
critical_obs_payload="$(jq -nc \
--arg recordedAt "${RECORDED_AT}" \
'{observations:[{observationCode:"POTASSIUM_MEQ_L",value:2.1,unit:"mEq/L",source:"LAB",recordedAt:$recordedAt,idempotencyKey:"script-critical-001"}]}')"
resp="$(request POST "${BASE_URL}/api/v1/encounters/${encounter_id}/observations" "${critical_obs_payload}")"
assert_status "201" "${resp}"
assert_json "${resp}" '.data.alertGenerated' 'true'
alert_id="$(jq -r '.data.alertId' "${resp}")"
if [[ -z "${alert_id}" || "${alert_id}" == "null" ]]; then
echo "Could not parse alert id from critical ingest."
exit 1
fi
echo "OK: critical alert generated (alert id = ${alert_id})"
echo ""
echo "[10/${TOTAL_STEPS}] Fetching observation history"
resp="$(request GET "${BASE_URL}/api/v1/encounters/${encounter_id}/observations?code=HEART_RATE&limit=10")"
assert_status "200" "${resp}"
history_count="$(jq -r '.data.items | length' "${resp}")"
if [[ "${history_count}" -lt 1 ]]; then
echo "Expected at least one HEART_RATE observation in history, got ${history_count}"
exit 1
fi
echo "OK: observation history returned ${history_count} item(s)"
echo ""
echo "[11/${TOTAL_STEPS}] Resolving unacknowledged alert returns 409"
resp="$(request POST "${BASE_URL}/api/v1/alerts/${alert_id}/resolve")"
assert_status "409" "${resp}"
assert_json "${resp}" '.error.code' 'ALERT_NOT_ACKNOWLEDGED'
echo "OK: resolve blocked before acknowledge"
echo ""
echo "[12/${TOTAL_STEPS}] Acknowledging alert"
ack_payload='{"clinicianId":"DR-SCRIPT","note":"Reviewing from verification script."}'
resp="$(request POST "${BASE_URL}/api/v1/alerts/${alert_id}/acknowledge" "${ack_payload}")"
assert_status "200" "${resp}"
assert_json "${resp}" '.data.status' 'Acknowledged'
echo "OK: alert acknowledged"
echo ""
echo "[13/${TOTAL_STEPS}] Resolving acknowledged alert"
resp="$(request POST "${BASE_URL}/api/v1/alerts/${alert_id}/resolve")"
assert_status "200" "${resp}"
assert_json "${resp}" '.data.status' 'Resolved'
echo "OK: alert resolved"
echo ""
echo "[14/${TOTAL_STEPS}] Rejecting implausible observation with 422"
implausible_payload="$(jq -nc \
--arg recordedAt "${RECORDED_AT}" \
'{observations:[{observationCode:"HEART_RATE",value:350,unit:"bpm",source:"DEVICE",recordedAt:$recordedAt}]}')"
resp="$(request POST "${BASE_URL}/api/v1/encounters/${encounter_id}/observations" "${implausible_payload}")"
assert_status "422" "${resp}"
assert_json "${resp}" '.error.code' 'OBSERVATION_OUT_OF_PLAUSIBLE_RANGE'
echo "OK: implausible value rejected"
echo ""
echo "[15/${TOTAL_STEPS}] Discharging encounter"
discharge_payload='{"status":"Discharged"}'
resp="$(request PATCH "${BASE_URL}/api/v1/encounters/${encounter_id}/status" "${discharge_payload}")"
assert_status "200" "${resp}"
echo "OK: encounter discharged"
echo ""
echo "[16/${TOTAL_STEPS}] Ingest against discharged encounter returns 409"
post_discharge_payload="$(jq -nc \
--arg recordedAt "${RECORDED_AT}" \
'{observations:[{observationCode:"HEART_RATE",value:78,unit:"bpm",source:"DEVICE",recordedAt:$recordedAt}]}')"
resp="$(request POST "${BASE_URL}/api/v1/encounters/${encounter_id}/observations" "${post_discharge_payload}")"
assert_status "409" "${resp}"
assert_json "${resp}" '.error.code' 'ENCOUNTER_NOT_ACTIVE'
echo "OK: ingest blocked for discharged encounter"
echo ""
echo "All ${TOTAL_STEPS} API + Redis checks passed."