feature: Observation Ingest, Synchronous Alert Detection, and Alert Lifecycle
This commit is contained in:
@@ -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);
|
||||
@@ -1,6 +1,7 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
.WriteTo.Console()
|
||||
@@ -18,23 +19,33 @@ try
|
||||
builder.Services.AddDbContext<AppDbContext>(opts =>
|
||||
opts.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
|
||||
|
||||
builder.Services.AddSingleton<IConnectionMultiplexer>(
|
||||
ConnectionMultiplexer.Connect(builder.Configuration["Redis:ConnectionString"]!));
|
||||
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
|
||||
ConnectionMultiplexer.Connect(sp.GetRequiredService<IConfiguration>()["Redis:ConnectionString"]!));
|
||||
|
||||
builder.Services.AddScoped<IPatientService, PatientService>();
|
||||
builder.Services.AddScoped<IEncounterService, EncounterService>();
|
||||
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.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.AddSwaggerGen();
|
||||
|
||||
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 redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
|
||||
await DataSeeder.SeedAsync(db, redis);
|
||||
@@ -71,8 +82,11 @@ catch (HostAbortedException)
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "Application failed to start.");
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
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 4–8 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" }
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user