Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
Stop consumers from committing past failed offsets, harden Rabbit/DataLake/gateway backpressure, dispose JsonDocument/MinIO correctly, and batch expensive DB/HTTP paths. Track progress in docs/performance.
This commit is contained in:
@@ -8,11 +8,16 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly MinioOptions _minioOpts;
|
||||
private readonly IMinioClient _minio;
|
||||
|
||||
public DischargeSummaryService(AppDbContext db, IOptions<MinioOptions> minioOpts)
|
||||
public DischargeSummaryService(
|
||||
AppDbContext db,
|
||||
IOptions<MinioOptions> minioOpts,
|
||||
IMinioClient minio)
|
||||
{
|
||||
_db = db;
|
||||
_minioOpts = minioOpts.Value;
|
||||
_minio = minio;
|
||||
}
|
||||
|
||||
public async Task<DischargeSummaryInfo> GetInfoAsync(Guid encounterId, CancellationToken ct = default)
|
||||
@@ -68,12 +73,11 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
|
||||
"DISCHARGE_SUMMARY_PENDING");
|
||||
}
|
||||
|
||||
var client = MinioClientFactory.Build(_minioOpts);
|
||||
var bucket = _minioOpts.BucketName;
|
||||
var objectKey = ObjectKey(encounterId);
|
||||
var ms = new MemoryStream();
|
||||
|
||||
await client.GetObjectAsync(new GetObjectArgs()
|
||||
await _minio.GetObjectAsync(new GetObjectArgs()
|
||||
.WithBucket(bucket)
|
||||
.WithObject(objectKey)
|
||||
.WithCallbackStream(stream => stream.CopyTo(ms)), ct);
|
||||
@@ -84,13 +88,12 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
|
||||
|
||||
private async Task<bool> ObjectExistsAsync(Guid encounterId, CancellationToken ct)
|
||||
{
|
||||
var client = MinioClientFactory.Build(_minioOpts);
|
||||
var bucket = _minioOpts.BucketName;
|
||||
var objectKey = ObjectKey(encounterId);
|
||||
|
||||
try
|
||||
{
|
||||
await client.StatObjectAsync(new StatObjectArgs()
|
||||
await _minio.StatObjectAsync(new StatObjectArgs()
|
||||
.WithBucket(bucket)
|
||||
.WithObject(objectKey), ct);
|
||||
return true;
|
||||
|
||||
@@ -74,13 +74,12 @@ public class EncounterService : IEncounterService
|
||||
|
||||
var encounterIds = encounters.Select(e => e.Id).ToList();
|
||||
|
||||
var news2ByEncounter = (await _db.News2Scores
|
||||
var news2ByEncounter = await _db.News2Scores
|
||||
.AsNoTracking()
|
||||
.Where(s => encounterIds.Contains(s.EncounterId))
|
||||
.OrderByDescending(s => s.CalculatedAt)
|
||||
.ToListAsync())
|
||||
.GroupBy(s => s.EncounterId)
|
||||
.ToDictionary(g => g.Key, g => g.First());
|
||||
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
|
||||
.ToDictionaryAsync(s => s.EncounterId);
|
||||
|
||||
var openAlertCounts = await _db.ClinicalAlerts
|
||||
.AsNoTracking()
|
||||
@@ -89,29 +88,26 @@ public class EncounterService : IEncounterService
|
||||
.Select(g => new { EncounterId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(x => x.EncounterId, x => x.Count);
|
||||
|
||||
var bundlesByEncounter = (await _db.SepsisBundles
|
||||
var bundlesByEncounter = await _db.SepsisBundles
|
||||
.AsNoTracking()
|
||||
.Where(b => encounterIds.Contains(b.EncounterId))
|
||||
.OrderByDescending(b => b.RecognizedAt)
|
||||
.ToListAsync())
|
||||
.GroupBy(b => b.EncounterId)
|
||||
.ToDictionary(g => g.Key, g => g.First());
|
||||
.Select(g => g.OrderByDescending(b => b.RecognizedAt).First())
|
||||
.ToDictionaryAsync(b => b.EncounterId);
|
||||
|
||||
var sofaByEncounter = (await _db.SofaScores
|
||||
var sofaByEncounter = await _db.SofaScores
|
||||
.AsNoTracking()
|
||||
.Where(s => encounterIds.Contains(s.EncounterId))
|
||||
.OrderByDescending(s => s.CalculatedAt)
|
||||
.ToListAsync())
|
||||
.GroupBy(s => s.EncounterId)
|
||||
.ToDictionary(g => g.Key, g => g.First());
|
||||
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
|
||||
.ToDictionaryAsync(s => s.EncounterId);
|
||||
|
||||
var gcsByEncounter = (await _db.GcsScores
|
||||
var gcsByEncounter = await _db.GcsScores
|
||||
.AsNoTracking()
|
||||
.Where(s => encounterIds.Contains(s.EncounterId))
|
||||
.OrderByDescending(s => s.CalculatedAt)
|
||||
.ToListAsync())
|
||||
.GroupBy(s => s.EncounterId)
|
||||
.ToDictionary(g => g.Key, g => g.First());
|
||||
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
|
||||
.ToDictionaryAsync(s => s.EncounterId);
|
||||
|
||||
var lastObservationByEncounter = await _db.Observations
|
||||
.AsNoTracking()
|
||||
@@ -246,8 +242,15 @@ public class EncounterService : IEncounterService
|
||||
});
|
||||
}
|
||||
|
||||
// Bound timeline payloads for long-stay encounters (recent window + row caps).
|
||||
const int maxEventsPerType = 500;
|
||||
var timelineCutoff = DateTimeOffset.UtcNow.AddDays(-7);
|
||||
|
||||
var observations = await _db.Observations
|
||||
.Where(o => o.EncounterId == encounterId)
|
||||
.AsNoTracking()
|
||||
.Where(o => o.EncounterId == encounterId && o.RecordedAt >= timelineCutoff)
|
||||
.OrderByDescending(o => o.RecordedAt)
|
||||
.Take(maxEventsPerType)
|
||||
.Select(o => new
|
||||
{
|
||||
type = "observation",
|
||||
@@ -260,7 +263,10 @@ public class EncounterService : IEncounterService
|
||||
events.AddRange(observations);
|
||||
|
||||
var alerts = await _db.ClinicalAlerts
|
||||
.Where(a => a.EncounterId == encounterId)
|
||||
.AsNoTracking()
|
||||
.Where(a => a.EncounterId == encounterId && a.TriggeredAt >= timelineCutoff)
|
||||
.OrderByDescending(a => a.TriggeredAt)
|
||||
.Take(maxEventsPerType)
|
||||
.Select(a => new
|
||||
{
|
||||
type = "alert",
|
||||
@@ -273,7 +279,10 @@ public class EncounterService : IEncounterService
|
||||
events.AddRange(alerts);
|
||||
|
||||
var orders = await _db.Orders
|
||||
.Where(o => o.EncounterId == encounterId)
|
||||
.AsNoTracking()
|
||||
.Where(o => o.EncounterId == encounterId && o.OrderedAt >= timelineCutoff)
|
||||
.OrderByDescending(o => o.OrderedAt)
|
||||
.Take(maxEventsPerType)
|
||||
.Select(o => new
|
||||
{
|
||||
type = "order",
|
||||
@@ -286,7 +295,10 @@ public class EncounterService : IEncounterService
|
||||
events.AddRange(orders);
|
||||
|
||||
var medications = await _db.MedicationAdministrations
|
||||
.Where(m => m.EncounterId == encounterId)
|
||||
.AsNoTracking()
|
||||
.Where(m => m.EncounterId == encounterId && m.AdministeredAt >= timelineCutoff)
|
||||
.OrderByDescending(m => m.AdministeredAt)
|
||||
.Take(maxEventsPerType)
|
||||
.Select(m => new
|
||||
{
|
||||
type = "medication",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
public interface IPhiAccessLogService
|
||||
{
|
||||
Task LogViewAsync(Guid patientId, string resourcePath);
|
||||
Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath);
|
||||
Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null);
|
||||
Task LogCreateAsync(Guid patientId, string resourcePath);
|
||||
Task LogUpdateAsync(Guid patientId, string resourcePath);
|
||||
|
||||
@@ -197,7 +197,6 @@ public class ObservationService : IObservationService
|
||||
if (encounter.Status != EncounterStatus.Active)
|
||||
throw new ValidationException("Encounter not active.", "ENCOUNTER_NOT_ACTIVE");
|
||||
|
||||
await using var tx = await _db.Database.BeginTransactionAsync(ct);
|
||||
try
|
||||
{
|
||||
var observation = new Observation
|
||||
@@ -267,11 +266,10 @@ public class ObservationService : IObservationService
|
||||
}, obs.EncounterId.ToString()));
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
await tx.CommitAsync(ct);
|
||||
}
|
||||
catch (DbUpdateException ex) when (IsUniqueViolation(ex))
|
||||
{
|
||||
await tx.RollbackAsync(ct);
|
||||
_db.ChangeTracker.Clear();
|
||||
// silent skip — idempotency key already applied
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,8 +113,9 @@ public class PatientService : IPatientService
|
||||
var path = _http.HttpContext?.Request.Path.Value ?? "/api/v1/patients";
|
||||
await _phiAccess.LogListAsync(path, patients.Count, q);
|
||||
|
||||
foreach (var p in patients)
|
||||
await _phiAccess.LogViewAsync(p.Id, $"{path}?page={page}");
|
||||
await _phiAccess.LogViewsAsync(
|
||||
patients.Select(p => p.Id).ToList(),
|
||||
$"{path}?page={page}");
|
||||
|
||||
return new PagedResult<Patient>(patients, page, pageSize, total);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,37 @@ public class PhiAccessLogService : IPhiAccessLogService
|
||||
public async Task LogViewAsync(Guid patientId, string resourcePath) =>
|
||||
await WriteAsync(PhiAccessType.View, patientId, resourcePath);
|
||||
|
||||
public async Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath)
|
||||
{
|
||||
if (patientIds.Count == 0) return;
|
||||
if (!_currentUser.IsAuthenticated || _currentUser.UserId is null) return;
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var userId = _currentUser.UserId.Value;
|
||||
var display = _currentUser.DisplayName ?? _currentUser.Username ?? "Unknown";
|
||||
var ip = _currentUser.IpAddress;
|
||||
var correlationId = _http.HttpContext?.Items["CorrelationId"]?.ToString();
|
||||
|
||||
foreach (var patientId in patientIds)
|
||||
{
|
||||
_db.PhiAccessLogs.Add(new PhiAccessLog
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
AccessType = PhiAccessType.View,
|
||||
PatientId = patientId,
|
||||
UserId = userId,
|
||||
UserDisplayName = display,
|
||||
ResourcePath = resourcePath,
|
||||
IpAddress = ip,
|
||||
CorrelationId = correlationId,
|
||||
AccessedAt = now
|
||||
});
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
_metrics.PhiAccessLogsTotal.WithLabels(PhiAccessType.View.ToDbString()).Inc(patientIds.Count);
|
||||
}
|
||||
|
||||
public async Task LogCreateAsync(Guid patientId, string resourcePath) =>
|
||||
await WriteAsync(PhiAccessType.Create, patientId, resourcePath);
|
||||
|
||||
|
||||
@@ -176,19 +176,21 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var running = new List<Task>();
|
||||
foreach (var ctx in _runs.Values)
|
||||
{
|
||||
if (ctx.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running)
|
||||
ctx.Cts.Cancel();
|
||||
if (ctx.ExecuteTask is not null)
|
||||
running.Add(ctx.ExecuteTask);
|
||||
}
|
||||
|
||||
var deadline = DateTimeOffset.UtcNow.AddSeconds(5);
|
||||
while (DateTimeOffset.UtcNow < deadline
|
||||
&& _runs.Values.Any(c =>
|
||||
c.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running))
|
||||
{
|
||||
await Task.Delay(50, cancellationToken);
|
||||
}
|
||||
if (running.Count == 0) return;
|
||||
|
||||
var all = Task.WhenAll(running);
|
||||
var completed = await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(5), cancellationToken));
|
||||
if (completed != all)
|
||||
_logger.LogWarning("Simulation stop timed out waiting for {Count} run task(s)", running.Count);
|
||||
}
|
||||
|
||||
private async Task<SimulationRunState> RegisterAndStartAsync(
|
||||
@@ -224,7 +226,7 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
|
||||
if (!_runs.TryAdd(runId, ctx))
|
||||
throw new ConflictException("Failed to register simulation run.", "SIMULATION_REGISTER_FAILED");
|
||||
|
||||
_ = Task.Run(() => ExecuteAsync(ctx, CancellationToken.None), CancellationToken.None);
|
||||
ctx.ExecuteTask = Task.Run(() => ExecuteAsync(ctx, CancellationToken.None), CancellationToken.None);
|
||||
|
||||
return state.Snapshot();
|
||||
}
|
||||
@@ -365,5 +367,6 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
|
||||
public SimulationRunState State { get; } = state;
|
||||
public CancellationTokenSource Cts { get; } = cts;
|
||||
public ScenarioFile Scenario { get; } = scenario;
|
||||
public Task? ExecuteTask { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user