feature: Ward Gateway Service (Local-First Clinical Path)

This commit is contained in:
voltsrage
2026-06-23 16:45:38 +08:00
parent d8e142fffe
commit 1bf8359097
100 changed files with 5474 additions and 4 deletions
@@ -0,0 +1,24 @@
using System.Text.Json;
public static class BufferedSyncWriter
{
public static void Enqueue(
GatewayDbContext db,
BufferedSyncItemType itemType,
object payload,
string idempotencyKey,
Guid encounterId,
DateTimeOffset recordedAt)
{
db.BufferedSyncItems.Add(new BufferedSyncItem
{
Id = Guid.NewGuid(),
ItemType = itemType,
Payload = JsonSerializer.Serialize(payload),
IdempotencyKey = idempotencyKey,
EncounterId = encounterId,
RecordedAt = recordedAt,
CreatedAt = DateTimeOffset.UtcNow
});
}
}
@@ -0,0 +1,87 @@
using Microsoft.EntityFrameworkCore;
public class EncounterReadService : IEncounterReadService
{
private readonly GatewayDbContext _db;
public EncounterReadService(GatewayDbContext db) => _db = db;
public async Task<List<WardEncounterSummary>> ListActiveAsync(string? department)
{
var q = _db.Encounters
.Include(e => e.Patient)
.Where(e => e.Status == EncounterStatus.Active);
if (!string.IsNullOrEmpty(department))
{
var dept = DepartmentExtensions.FromDbString(department);
q = q.Where(e => e.Department == dept);
}
var encounters = await q
.OrderByDescending(e => e.AdmittedAt)
.ToListAsync();
if (encounters.Count == 0)
return [];
var encounterIds = encounters.Select(e => e.Id).ToList();
var openAlertCounts = await _db.ClinicalAlerts
.AsNoTracking()
.Where(a => encounterIds.Contains(a.EncounterId) && a.Status == AlertStatus.Open)
.GroupBy(a => a.EncounterId)
.Select(g => new { EncounterId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.EncounterId, x => x.Count);
return encounters.Select(e => new WardEncounterSummary(
e.Id,
e.Patient.Mrn,
e.Patient.FirstName,
e.Patient.LastName,
e.Department,
e.RoomBed,
e.AttendingPhysician,
e.AdmittedAt,
openAlertCounts.GetValueOrDefault(e.Id),
News2Score: null,
QsofaScore: null,
SepsisBundleStatus: null)).ToList();
}
public async Task<EncounterDetail?> GetByIdAsync(Guid id)
{
var enc = await _db.Encounters
.Include(e => e.Patient)
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == id);
if (enc is null) return null;
var observations = await _db.Observations
.AsNoTracking()
.Where(o => o.EncounterId == id)
.OrderByDescending(o => o.RecordedAt)
.Take(10)
.ToListAsync();
var alerts = await _db.ClinicalAlerts
.AsNoTracking()
.Where(a => a.EncounterId == id && a.Status == AlertStatus.Open)
.OrderByDescending(a => a.TriggeredAt)
.ToListAsync();
return new EncounterDetail(
enc.Id,
enc.PatientId,
enc.Patient.Mrn,
enc.Patient.FirstName,
enc.Patient.LastName,
enc.Department,
enc.Status,
enc.RoomBed,
enc.AttendingPhysician,
enc.AdmittedAt,
observations,
alerts);
}
}
@@ -0,0 +1,5 @@
public interface IEncounterReadService
{
Task<List<WardEncounterSummary>> ListActiveAsync(string? department);
Task<EncounterDetail?> GetByIdAsync(Guid id);
}
@@ -0,0 +1,6 @@
public interface ILocalAlertService
{
Task<LocalClinicalAlert> AcknowledgeAsync(Guid id, AcknowledgeAlertRequest req, string clinicianId);
Task<LocalClinicalAlert> ResolveAsync(Guid id);
Task<PagedResult<LocalClinicalAlert>> ListAsync(Guid? encounterId, string? status, int page, int pageSize);
}
@@ -0,0 +1,4 @@
public interface ILocalObservationService
{
Task<LocalIngestResult> IngestAsync(Guid encounterId, IngestObservationRequest req);
}
@@ -0,0 +1,10 @@
public interface IObservationQueryService
{
Task<CursorPage<LocalObservation>> GetHistoryAsync(
Guid encounterId,
string? code,
DateTimeOffset? from,
DateTimeOffset? to,
int limit,
string? cursorToken);
}
@@ -0,0 +1,77 @@
using Microsoft.EntityFrameworkCore;
public class LocalAlertService : ILocalAlertService
{
private readonly GatewayDbContext _db;
public LocalAlertService(GatewayDbContext db) => _db = db;
public async Task<LocalClinicalAlert> AcknowledgeAsync(
Guid id, AcknowledgeAlertRequest req, string clinicianId)
{
var alert = await _db.ClinicalAlerts.FindAsync(id)
?? throw new NotFoundException("Alert not found.", "ALERT_NOT_FOUND");
if (alert.Status is not (AlertStatus.Open or AlertStatus.Escalated))
throw new ConflictException("Alert cannot be acknowledged.", "ALERT_NOT_ACKNOWLEDGEABLE");
alert.Status = AlertStatus.Acknowledged;
alert.AcknowledgedAt = DateTimeOffset.UtcNow;
alert.AcknowledgedBy = clinicianId;
BufferedSyncWriter.Enqueue(_db, BufferedSyncItemType.Ack, new
{
clientRef = Guid.NewGuid(),
alert.ClientAlertId,
clinicianId,
acknowledgedAt = alert.AcknowledgedAt,
req.Note
}, $"ack:{alert.ClientAlertId}:{alert.AcknowledgedAt:o}", alert.EncounterId, alert.AcknowledgedAt!.Value);
await _db.SaveChangesAsync();
return alert;
}
public async Task<LocalClinicalAlert> ResolveAsync(Guid id)
{
var alert = await _db.ClinicalAlerts.FindAsync(id)
?? throw new NotFoundException("Alert not found.", "ALERT_NOT_FOUND");
if (alert.Status != AlertStatus.Acknowledged)
throw new ConflictException("Alert must be acknowledged first.", "ALERT_NOT_ACKNOWLEDGED");
alert.Status = AlertStatus.Resolved;
alert.ResolvedAt = DateTimeOffset.UtcNow;
BufferedSyncWriter.Enqueue(_db, BufferedSyncItemType.Resolve, new
{
clientRef = Guid.NewGuid(),
alert.ClientAlertId,
clinicianId = alert.AcknowledgedBy,
resolvedAt = alert.ResolvedAt,
note = (string?)null
}, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value);
await _db.SaveChangesAsync();
return alert;
}
public async Task<PagedResult<LocalClinicalAlert>> ListAsync(
Guid? encounterId, string? status, int page, int pageSize)
{
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize, 1, 100);
var q = _db.ClinicalAlerts.AsNoTracking().AsQueryable();
if (encounterId.HasValue) q = q.Where(a => a.EncounterId == encounterId);
if (!string.IsNullOrEmpty(status))
{
var parsedStatus = AlertStatusExtensions.FromDbString(status);
q = q.Where(a => a.Status == parsedStatus);
}
var total = await q.CountAsync();
var items = await q.OrderByDescending(a => a.TriggeredAt)
.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync();
return new PagedResult<LocalClinicalAlert>(items, page, pageSize, total);
}
}
@@ -0,0 +1,174 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using StackExchange.Redis;
public class LocalObservationService : ILocalObservationService
{
private readonly GatewayDbContext _db;
private readonly IConnectionMultiplexer _redis;
private readonly LocalWarningEvaluator _warnings;
private readonly LocalPagingPublisher _paging;
private readonly ILogger<LocalObservationService> _logger;
public LocalObservationService(
GatewayDbContext db,
IConnectionMultiplexer redis,
LocalWarningEvaluator warnings,
LocalPagingPublisher paging,
ILogger<LocalObservationService> logger)
{
_db = db;
_redis = redis;
_warnings = warnings;
_paging = paging;
_logger = logger;
}
public async Task<LocalIngestResult> IngestAsync(Guid encounterId, IngestObservationRequest req)
{
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("Encounter is not active.", "ENCOUNTER_NOT_ACTIVE");
if (!string.IsNullOrEmpty(req.IdempotencyKey))
{
var existing = await _db.Observations.AsNoTracking()
.FirstOrDefaultAsync(o => o.IdempotencyKey == req.IdempotencyKey);
if (existing is not null)
return LocalIngestResult.Duplicate(existing);
}
if (!PlausibilityValidator.IsPlausible(req.ObservationCode, req.Value, out var reason))
throw new ValidationException(reason!, "OBSERVATION_OUT_OF_PLAUSIBLE_RANGE");
await using var tx = await _db.Database.BeginTransactionAsync();
try
{
var observation = new LocalObservation
{
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);
var threshold = await LoadThresholdAsync(req.ObservationCode);
if (threshold is null)
throw new ValidationException("Unknown observation code.", "UNKNOWN_OBSERVATION_CODE");
LocalClinicalAlert? alert = null;
if (IsCriticalBreach(req.Value, threshold))
{
var triggeredAt = DateTimeOffset.UtcNow;
alert = new LocalClinicalAlert
{
Id = Guid.NewGuid(),
ClientAlertId = 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 = triggeredAt
};
_db.ClinicalAlerts.Add(alert);
BufferedSyncWriter.Enqueue(_db, BufferedSyncItemType.Alert, new
{
alert.ClientAlertId,
alert.EncounterId,
alertType = alert.AlertType.ToDbString(),
severity = alert.Severity.ToDbString(),
alert.Details,
generatedAt = triggeredAt
}, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt);
await _paging.PublishCriticalAsync(alert, encounter);
}
if (alert is null)
await _warnings.TryEvaluateAsync(
observation.Id, encounterId, encounter.PatientId,
req.ObservationCode, req.Value, threshold);
BufferedSyncWriter.Enqueue(_db, BufferedSyncItemType.Observation, new
{
clientRef = observation.Id,
req.IdempotencyKey,
encounterId,
req.ObservationCode,
req.Value,
req.Unit,
source = req.Source.ToDbString(),
req.RecordedAt
}, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt);
await _db.SaveChangesAsync();
await tx.CommitAsync();
return LocalIngestResult.Created(observation, alert);
}
catch (DbUpdateException ex) when (IsUniqueViolation(ex))
{
await tx.RollbackAsync();
var existing = await _db.Observations.AsNoTracking()
.FirstOrDefaultAsync(o => o.IdempotencyKey == req.IdempotencyKey);
if (existing is not null) return LocalIngestResult.Duplicate(existing);
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!);
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 bool IsUniqueViolation(DbUpdateException ex) =>
ex.InnerException is Npgsql.PostgresException pg && pg.SqlState == "23505";
}
@@ -0,0 +1,58 @@
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
public sealed class LocalPagingPublisher
{
private readonly RabbitMqOptions _opts;
private readonly ILogger<LocalPagingPublisher> _logger;
public LocalPagingPublisher(IOptions<RabbitMqOptions> opts, ILogger<LocalPagingPublisher> logger)
{
_opts = opts.Value;
_logger = logger;
}
public Task PublishCriticalAsync(LocalClinicalAlert alert, ReplicaEncounter encounter)
{
try
{
var factory = new ConnectionFactory
{
HostName = _opts.Host,
Port = _opts.Port,
UserName = _opts.Username,
Password = _opts.Password
};
using var conn = factory.CreateConnection("gateway-publisher");
using var channel = conn.CreateModel();
var payload = JsonSerializer.Serialize(new
{
alertId = alert.Id,
encounterId = alert.EncounterId,
details = alert.Details,
attendingPhysician = encounter.AttendingPhysician
});
var body = Encoding.UTF8.GetBytes(payload);
channel.BasicPublish(
RabbitMqTopologyProvisioner.Exchange,
RabbitMqTopologyProvisioner.PagingKey,
body: body);
_logger.LogInformation(
"Published critical alert {AlertId} to paging queue for encounter {EncounterId}",
alert.Id, alert.EncounterId);
}
catch (Exception ex)
{
_logger.LogError(ex,
"Failed to publish critical alert {AlertId} to paging queue — alert persisted locally",
alert.Id);
}
return Task.CompletedTask;
}
}
@@ -0,0 +1,75 @@
using Microsoft.EntityFrameworkCore;
public class LocalWarningEvaluator
{
private readonly GatewayDbContext _db;
private readonly ILogger<LocalWarningEvaluator> _logger;
public LocalWarningEvaluator(GatewayDbContext db, ILogger<LocalWarningEvaluator> logger)
{
_db = db;
_logger = logger;
}
public async Task<bool> TryEvaluateAsync(
Guid observationId, Guid encounterId, Guid patientId,
string observationCode, decimal value, ThresholdCacheEntry threshold)
{
if (!IsWarningBreach(value, threshold)) return false;
if (IsCriticalBreach(value, threshold)) return false;
var alertType = AlertTypeExtensions.WarningFor(observationCode);
var clientAlertId = Guid.NewGuid();
var triggeredAt = DateTimeOffset.UtcNow;
var details = BuildWarningDetails(observationCode, value, threshold);
var exists = await _db.ClinicalAlerts.AnyAsync(a =>
a.EncounterId == encounterId
&& a.AlertType == alertType
&& (a.Status == AlertStatus.Open || a.Status == AlertStatus.Acknowledged));
if (exists) return false;
var alert = new LocalClinicalAlert
{
Id = Guid.NewGuid(),
ClientAlertId = clientAlertId,
EncounterId = encounterId,
PatientId = patientId,
ObservationId = observationId,
AlertType = alertType,
Severity = AlertSeverity.Warning,
Details = details,
Status = AlertStatus.Open,
TriggeredAt = triggeredAt
};
_db.ClinicalAlerts.Add(alert);
BufferedSyncWriter.Enqueue(_db, BufferedSyncItemType.Alert, new
{
clientAlertId,
encounterId,
alertType = alertType.ToDbString(),
severity = AlertSeverity.Warning.ToDbString(),
details,
generatedAt = triggeredAt
}, $"alert:{clientAlertId}", encounterId, triggeredAt);
_logger.LogInformation(
"WARNING alert {AlertId} created locally for encounter {EncounterId}",
alert.Id, encounterId);
return true;
}
private static bool IsWarningBreach(decimal value, ThresholdCacheEntry t) =>
(t.WarningHigh.HasValue && value > t.WarningHigh.Value) ||
(t.WarningLow.HasValue && value < t.WarningLow.Value);
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 BuildWarningDetails(string code, decimal value, ThresholdCacheEntry t) =>
t.WarningHigh.HasValue && value > t.WarningHigh.Value
? $"{code} value {value} is above warning high of {t.WarningHigh}."
: $"{code} value {value} is below warning low of {t.WarningLow}.";
}
@@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore;
public class ObservationQueryService : IObservationQueryService
{
private readonly GatewayDbContext _db;
public ObservationQueryService(GatewayDbContext db) => _db = db;
public async Task<CursorPage<LocalObservation>> 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)
{
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)
.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<LocalObservation>(items, nextCursor, hasMore);
}
}
@@ -0,0 +1,47 @@
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.
private static readonly Dictionary<string, (decimal Min, decimal Max)> _ranges = new()
{
["HEART_RATE"] = (1, 300),
["TEMP_C"] = (15, 50),
["POTASSIUM_MEQ_L"] = (0.1m, 12),
["SPO2"] = (50, 100),
["RESP_RATE"] = (1, 80),
["WBC_K_UL"] = (0.1m, 500),
["GLUCOSE_MG_DL"] = (10, 1000),
["SYSTOLIC_BP"] = (40, 300),
["DIASTOLIC_BP"] = (20, 200),
["LACTATE_MMOL_L"] = (0.1m, 30),
["AVPU"] = (0, 3),
["SUPPLEMENTAL_O2"] = (0, 1),
["GCS_EYE"] = (1, 4),
["GCS_VERBAL"] = (1, 5),
["GCS_MOTOR"] = (1, 6),
["PAO2_MMHG"] = (20, 600),
["FIO2_PCT"] = (21, 100),
["PLATELET_K_UL"] = (1, 1500),
["BILIRUBIN_MG_DL"] = (0.1m, 50),
["CREATININE_MG_DL"] = (0.1m, 20),
["URINE_OUTPUT_ML_H"] = (0, 500),
};
public static bool IsPlausible(string observationCode, decimal value, out string? reason)
{
if (!_ranges.TryGetValue(observationCode, out var range))
{
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;
}
}