Harden API memory and CPU usage across Phases 19–22.
CI / changes (push) Successful in 17s
dotnet8-ci / build-and-test (push) Successful in 8m23s
CI / backend (push) Successful in 8m24s
node-ci / build (push) Failing after 2m1s
CI / frontend (push) Failing after 2m2s

Bound list/PDF payloads, stream MinIO I/O with cancellation, paginate history and FHIR $everything, tighten OCR lifetimes/buffers, and add phase tracking docs.
This commit is contained in:
2026-11-30 23:55:56 +08:00
parent 192cb36dc7
commit a17bc2b734
46 changed files with 1677 additions and 215 deletions
@@ -1,7 +1,4 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args;
/// <summary>
/// Runs migrate / demo seed / MinIO bucket ensure after Kestrel is listening.
@@ -38,19 +35,12 @@ public sealed class AppBootstrapHostedService : BackgroundService
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync(stoppingToken);
await DataSeeder.SeedAsync(db);
var minio = scope.ServiceProvider.GetRequiredService<IMinioClient>();
var minioOpts = scope.ServiceProvider.GetRequiredService<IOptions<MinioOptions>>().Value;
if (!await minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(minioOpts.BucketName), stoppingToken))
{
await minio.MakeBucketAsync(
new MakeBucketArgs().WithBucket(minioOpts.BucketName), stoppingToken);
_logger.LogInformation("Created MinIO bucket {Bucket}", minioOpts.BucketName);
}
await DataSeeder.SeedAsync(db, stoppingToken);
var storage = scope.ServiceProvider.GetRequiredService<IDocumentStorageService>();
await storage.EnsureBucketAsync(stoppingToken);
_logger.LogInformation("MinIO bucket ensure completed.");
await SeedDocumentStorage.EnsureAsync(db, storage, _logger, stoppingToken);
_startupHealthCheck.StartupCompleted = true;
@@ -147,10 +147,10 @@ public class OcrProcessingService : BackgroundService
try
{
await using var documentStream = await storage.DownloadAsync(document.ObjectKey);
var extraction = await ocr.ExtractAsync(documentStream, document.ContentType);
await using var documentStream = await storage.DownloadAsync(document.ObjectKey, ct);
var extraction = await ocr.ExtractAsync(documentStream, document.ContentType, ct);
await preFiller.PreFillAsync(batch.Id, batch.BatchType, extraction);
await preFiller.PreFillAsync(batch.Id, batch.BatchType, extraction, ct);
var fieldConfidences = extraction.Fields
.GroupBy(f => f.FieldName, StringComparer.Ordinal)
@@ -163,7 +163,7 @@ public class OcrProcessingService : BackgroundService
BatchId = batch.Id,
Provider = _options.Provider,
FieldConfidencesJson = JsonSerializer.Serialize(fieldConfidences),
RawText = extraction.RawText,
RawText = TruncateRawText(extraction.RawText),
DurationMs = extraction.DurationMs,
ProcessedAt = processedAt
});
@@ -213,4 +213,16 @@ public class OcrProcessingService : BackgroundService
batch.Id, ex.Message);
}
}
/// <summary>Caps persisted OCR text to limit DB/LOH growth; draft GET uses confidences only.</summary>
internal const int MaxRawTextChars = 64 * 1024;
private static string? TruncateRawText(string? rawText)
{
if (string.IsNullOrEmpty(rawText))
return rawText;
return rawText.Length <= MaxRawTextChars
? rawText
: rawText[..MaxRawTextChars];
}
}
@@ -133,7 +133,7 @@ public class PromotionRetryService : BackgroundService
$"Batch {batchId} is in Approved status but has no ApprovedByUserId");
// Attempt promotion with a unique idempotency key per attempt
await promotionService.PromoteAsync(batchId, approverUserId);
await promotionService.PromoteAsync(batchId, approverUserId, ct);
// --- Success path ---
DiagnosticsMetrics.PromotionRetryTotal.WithLabels("success").Inc();
@@ -146,32 +146,41 @@ public class DigitizationBatchesController : ControllerBase
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetDocument(Guid id)
{
var batch = await _batches.GetByIdAsync(id);
var batchMeta = await _db.DigitizationBatches
.AsNoTracking()
.Where(b => b.Id == id)
.Select(b => new { b.DocumentRef })
.FirstOrDefaultAsync();
if (batch.DocumentRef == "live-capture")
if (batchMeta is null)
return NotFound(ApiResponse<object>.Fail(404, "Batch not found.", "BATCH_NOT_FOUND"));
if (batchMeta.DocumentRef == "live-capture" || string.IsNullOrEmpty(batchMeta.DocumentRef))
return NotFound(ApiResponse<object>.Fail(
404, "This batch has no scanned document.", "NO_DOCUMENT"));
var scanned = await _db.ScannedDocuments
var contentType = await _db.ScannedDocuments
.AsNoTracking()
.FirstOrDefaultAsync(d => d.BatchId == id);
var contentType = scanned?.ContentType ?? "application/octet-stream";
.Where(d => d.BatchId == id)
.Select(d => d.ContentType)
.FirstOrDefaultAsync() ?? "application/octet-stream";
await RecordDocumentAccessAsync(id);
try
{
if (!await _storage.ObjectExistsAsync(batch.DocumentRef))
return NotFound(ApiResponse<object>.Fail(
404,
"Scanned document is missing from storage. Re-upload the batch or restore the object.",
"DOCUMENT_NOT_FOUND"));
var stream = await _storage.DownloadAsync(batch.DocumentRef);
var stream = await _storage.DownloadAsync(
batchMeta.DocumentRef, HttpContext.RequestAborted);
Response.Headers.CacheControl = "private, max-age=300";
return File(stream, contentType);
}
catch (Minio.Exceptions.ObjectNotFoundException)
{
return NotFound(ApiResponse<object>.Fail(
404,
"Scanned document is missing from storage. Re-upload the batch or restore the object.",
"DOCUMENT_NOT_FOUND"));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return StatusCode(503, ApiResponse<object>.Fail(
@@ -54,12 +54,15 @@ public class FhirPatientController : ControllerBase
[HttpGet("{id}/$everything")]
[ProducesResponseType(typeof(Bundle), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(OperationOutcome), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Everything(string id)
public async Task<IActionResult> Everything(
string id,
[FromQuery(Name = "_count")] int count = 100,
[FromQuery(Name = "_offset")] int offset = 0)
{
var bundle = await _fhir.GetPatientEverythingAsync(Guid.Parse(id));
var bundle = await _fhir.GetPatientEverythingAsync(Guid.Parse(id), count, offset);
if (bundle is null)
return NotFound(FhirErrorHelper.NotFound("Patient", id));
return Ok(bundle);
}
}
}
@@ -41,9 +41,12 @@ public class PatientsController : ControllerBase
[HttpGet("{patientId:guid}/digitization-history")]
[ProducesResponseType(typeof(ApiResponse<PatientDigitizationHistoryResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetDigitizationHistory(Guid patientId)
public async Task<IActionResult> GetDigitizationHistory(
Guid patientId,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
{
var history = await _history.GetPatientHistoryAsync(patientId);
var history = await _history.GetPatientHistoryAsync(patientId, page, pageSize);
return Ok(ApiResponse<PatientDigitizationHistoryResponse>.Ok(history));
}
}
+2 -2
View File
@@ -24,9 +24,9 @@ public static class DataSeeder
private static readonly Guid Patient4Id = Guid.Parse("b1000000-0000-0000-0000-000000000004");
private static readonly Guid Patient5Id = Guid.Parse("b1000000-0000-0000-0000-000000000005");
public static async Task SeedAsync(AppDbContext db)
public static async Task SeedAsync(AppDbContext db, CancellationToken ct = default)
{
if (await db.Users.AnyAsync()) return;
if (await db.Users.AnyAsync(ct)) return;
// ── Users (2 per role) ────────────────────────────────────────────────
var users = new[]
@@ -61,17 +61,35 @@ public static class SeedDocumentStorage
logger.LogInformation("Seeded {Count} missing ScannedDocument rows", missingDocs.Count);
}
// Prefer ensuring objects only for keys we just registered as missing docs,
// plus a single pass for remaining keys via EnsureObjectAsync (Stat+Put if needed).
// Cap bootstrap MinIO work so restarts on large DBs stay bounded.
const int maxObjectEnsuresPerBootstrap = 200;
var keysToEnsure = missingDocs
.Select(d => d.ObjectKey)
.Concat(batches.Select(b => b.DocumentRef))
.Distinct(StringComparer.Ordinal)
.Take(maxObjectEnsuresPerBootstrap)
.ToList();
var uploaded = 0;
foreach (var batch in batches)
foreach (var objectKey in keysToEnsure)
{
ct.ThrowIfCancellationRequested();
if (!await storage.ObjectExistsAsync(batch.DocumentRef))
if (!await storage.ObjectExistsAsync(objectKey, ct))
{
await storage.EnsureObjectAsync(batch.DocumentRef, MinimalPdf, "application/pdf");
await storage.EnsureObjectAsync(objectKey, MinimalPdf, "application/pdf", ct);
uploaded++;
}
}
if (batches.Count > maxObjectEnsuresPerBootstrap)
{
logger.LogWarning(
"SeedDocumentStorage capped MinIO ensure at {Cap} of {Total} batch keys; remaining keys will be ensured on later bootstraps or first access",
maxObjectEnsuresPerBootstrap, batches.Count);
}
if (uploaded > 0)
logger.LogInformation("Uploaded {Count} placeholder scan PDFs to object storage", uploaded);
}
@@ -6,6 +6,9 @@ using Task = System.Threading.Tasks.Task;
public class FhirJsonOutputFormatter : TextOutputFormatter
{
private static readonly Lazy<FhirJsonSerializer> Serializer = new(() =>
new FhirJsonSerializer(new SerializerSettings { Pretty = false }));
public FhirJsonOutputFormatter()
{
SupportedMediaTypes.Add("application/fhir+json");
@@ -24,8 +27,7 @@ public class FhirJsonOutputFormatter : TextOutputFormatter
var resource = context.Object as Resource;
if (resource is null) return;
var serializer = new FhirJsonSerializer(new SerializerSettings { Pretty = true });
var json = serializer.SerializeToString(resource);
var json = Serializer.Value.SerializeToString(resource);
await context.HttpContext.Response.WriteAsync(json, selectedEncoding);
}
}
}
@@ -4,5 +4,8 @@ public record PatientDigitizationHistoryResponse(
int PromotedBatches,
int SupersededBatches,
int PendingBatches,
int Page,
int PageSize,
int TotalPages,
IReadOnlyList<DigitizationHistoryEntry> Entries
);
+14
View File
@@ -1,5 +1,7 @@
using System.Text;
using System.Threading.RateLimiting;
using Azure;
using Azure.AI.DocumentIntelligence;
using FluentValidation;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
@@ -62,9 +64,21 @@ try
builder.Services.AddSingleton<ImagePreprocessor>();
if (ocrOptions.Provider == "azure")
{
builder.Services.AddSingleton(sp =>
{
var opts = sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<OcrOptions>>()
.Value.Azure;
return new DocumentIntelligenceClient(
new Uri(opts.Endpoint),
new AzureKeyCredential(opts.ApiKey));
});
builder.Services.AddScoped<IOcrService, AzureDocumentOcrService>();
}
else
{
builder.Services.AddScoped<IOcrService, TesseractOcrService>();
}
builder.Services.AddScoped<OcrDraftPreFiller>();
builder.Services.AddHostedService<OcrProcessingService>();
+4 -1
View File
@@ -189,7 +189,10 @@ public class BatchService : IBatchService
BatchStatus? status, BatchType? batchType, Guid? assignedTo, BatchTrack? track,
int page, int pageSize, string sortBy = "createdAt", string sortDirection = "desc")
{
var query = _db.DigitizationBatches.AsQueryable();
pageSize = Math.Clamp(pageSize, 1, 100);
page = Math.Max(1, page);
var query = _db.DigitizationBatches.AsNoTracking().AsQueryable();
if (status.HasValue)
query = query.Where(b => b.Status == status.Value);
@@ -65,6 +65,7 @@ public class CoverSheetService : ICoverSheetService
public async Task<CoverSheet?> LookupByCodeAsync(string code)
{
return await _db.CoverSheets
.AsNoTracking()
.Include(c => c.Patient)
.Include(c => c.AssignToUser)
.Include(c => c.Batch)
@@ -74,6 +75,7 @@ public class CoverSheetService : ICoverSheetService
public async Task<CoverSheet?> LookupByIdAsync(Guid id)
{
return await _db.CoverSheets
.AsNoTracking()
.Include(c => c.Patient)
.Include(c => c.AssignToUser)
.Include(c => c.Batch)
@@ -85,6 +87,11 @@ public class CoverSheetService : ICoverSheetService
if (ids.Count == 0)
return new List<CoverSheet>();
if (ids.Count > 100)
throw new ValidationException(
"At most 100 cover sheet IDs are allowed per batch PDF request.",
"COVER_SHEET_BATCH_PDF_LIMIT");
var idSet = ids.Distinct().ToList();
var sheets = await _db.CoverSheets
.AsNoTracking()
@@ -120,6 +127,9 @@ public class CoverSheetService : ICoverSheetService
public async Task<List<CoverSheet>> ListAsync(
bool? isUsed, Guid? patientId, int page, int pageSize)
{
pageSize = Math.Clamp(pageSize, 1, 100);
page = Math.Max(1, page);
var query = _db.CoverSheets
.AsNoTracking()
.Include(c => c.Patient)
@@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore;
public class DigitizationHistoryService : IDigitizationHistoryService
{
private const int MaxAuditEventsPerBatch = 50;
private readonly AppDbContext _db;
public DigitizationHistoryService(AppDbContext db)
@@ -9,10 +10,14 @@ public class DigitizationHistoryService : IDigitizationHistoryService
_db = db;
}
public async Task<PatientDigitizationHistoryResponse> GetPatientHistoryAsync(Guid patientId)
public async Task<PatientDigitizationHistoryResponse> GetPatientHistoryAsync(
Guid patientId, int page = 1, int pageSize = 20)
{
// Verify the patient exists (has at least one batch)
pageSize = Math.Clamp(pageSize, 1, 50);
page = Math.Max(1, page);
var hasBatches = await _db.DigitizationBatches
.AsNoTracking()
.AnyAsync(b => b.PatientId == patientId);
if (!hasBatches)
@@ -20,37 +25,70 @@ public class DigitizationHistoryService : IDigitizationHistoryService
$"No digitization history found for patient {patientId}.",
"PATIENT_HISTORY_NOT_FOUND");
// Load all batches for this patient with their relationships
var batches = await _db.DigitizationBatches
.Include(b => b.DraftObservations)
.Include(b => b.Events)
.ThenInclude(e => e.Actor)
.Include(b => b.EnteredByUser)
.Include(b => b.VerifiedByUser)
.Include(b => b.ApprovedByUser)
var statusCounts = await _db.DigitizationBatches
.AsNoTracking()
.Where(b => b.PatientId == patientId)
.OrderByDescending(b => b.CreatedAt)
.GroupBy(b => b.Status)
.Select(g => new { Status = g.Key, Count = g.Count() })
.ToListAsync();
// For each promoted batch, count live vs superseded observations
var promotedBatchIds = batches
var totalBatches = statusCounts.Sum(s => s.Count);
var promotedBatches = statusCounts
.Where(s => s.Status == BatchStatus.Promoted)
.Sum(s => s.Count);
var pendingBatches = statusCounts
.Where(s => s.Status != BatchStatus.Promoted && s.Status != BatchStatus.Rejected)
.Sum(s => s.Count);
var totalPages = Math.Max(1, (int)Math.Ceiling(totalBatches / (double)pageSize));
var batchPage = await _db.DigitizationBatches
.AsNoTracking()
.Where(b => b.PatientId == patientId)
.OrderByDescending(b => b.CreatedAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(b => new
{
b.Id,
b.Status,
b.BatchType,
b.Track,
b.SupersedesBatchId,
b.CreatedAt,
b.PromotedAt,
b.PromotionEncounterId,
b.EnteredByUserId,
EnteredByUserName = b.EnteredByUser != null ? b.EnteredByUser.FullName : null,
b.VerifiedByUserId,
VerifiedByUserName = b.VerifiedByUser != null ? b.VerifiedByUser.FullName : null,
b.ApprovedByUserId,
ApprovedByUserName = b.ApprovedByUser != null ? b.ApprovedByUser.FullName : null,
DraftObservationCount = b.DraftObservations.Count,
})
.ToListAsync();
var pageBatchIds = batchPage.Select(b => b.Id).ToList();
var promotedPageIds = batchPage
.Where(b => b.Status == BatchStatus.Promoted)
.Select(b => b.Id)
.ToList();
var liveObservationCounts = await _db.LiveObservations
.Where(o => promotedBatchIds.Contains(o.SourceBatchId))
.GroupBy(o => new { o.SourceBatchId, o.IsSuperseded })
.Select(g => new
{
g.Key.SourceBatchId,
g.Key.IsSuperseded,
Count = g.Count()
})
.ToListAsync();
var liveObservationCounts = promotedPageIds.Count == 0
? []
: await _db.LiveObservations
.AsNoTracking()
.Where(o => promotedPageIds.Contains(o.SourceBatchId))
.GroupBy(o => new { o.SourceBatchId, o.IsSuperseded })
.Select(g => new
{
g.Key.SourceBatchId,
g.Key.IsSuperseded,
Count = g.Count()
})
.ToListAsync();
// Build a lookup: batchId -> (activeCount, supersededCount)
var obsCountLookup = promotedBatchIds.ToDictionary(
var obsCountLookup = promotedPageIds.ToDictionary(
id => id,
id =>
{
@@ -61,17 +99,58 @@ public class DigitizationHistoryService : IDigitizationHistoryService
return (Active: active, Superseded: superseded);
});
// Build a lookup for "has been superseded" — batches that appear as
// SupersedesBatchId on another batch that reached Promoted
var supersededByLookup = await _db.DigitizationBatches
.Where(b => b.SupersedesBatchId.HasValue
&& b.Status == BatchStatus.Promoted
&& promotedBatchIds.Contains(b.SupersedesBatchId.Value))
.ToDictionaryAsync(
b => b.SupersedesBatchId!.Value,
b => b.Id);
var supersededByLookup = promotedPageIds.Count == 0
? new Dictionary<Guid, Guid>()
: await _db.DigitizationBatches
.AsNoTracking()
.Where(b => b.SupersedesBatchId.HasValue
&& b.Status == BatchStatus.Promoted
&& promotedPageIds.Contains(b.SupersedesBatchId.Value))
.ToDictionaryAsync(
b => b.SupersedesBatchId!.Value,
b => b.Id);
var entries = batches.Select(b =>
// Cap audit trail: newest MaxAuditEventsPerBatch events per batch on this page.
var events = pageBatchIds.Count == 0
? []
: await _db.DigitizationEvents
.AsNoTracking()
.Where(e => pageBatchIds.Contains(e.BatchId))
.OrderByDescending(e => e.OccurredAt)
.Select(e => new
{
e.BatchId,
EventType = e.EventType,
e.OccurredAt,
e.ActorUserId,
ActorName = e.Actor != null ? e.Actor.FullName : "Unknown",
e.MetadataJson
})
.ToListAsync();
var auditByBatch = events
.GroupBy(e => e.BatchId)
.ToDictionary(
g => g.Key,
g => g.Take(MaxAuditEventsPerBatch)
.OrderBy(e => e.OccurredAt)
.Select(e => new DigitizationEventSummary(
e.EventType.ToDbString(),
e.OccurredAt,
e.ActorUserId,
e.ActorName,
e.MetadataJson))
.ToList());
// SupersededBatches is global for the patient (not page-local).
var supersededBatchCount = await _db.DigitizationBatches
.AsNoTracking()
.Where(b => b.PatientId == patientId && b.Status == BatchStatus.Promoted)
.Where(b => _db.DigitizationBatches.Any(s =>
s.SupersedesBatchId == b.Id && s.Status == BatchStatus.Promoted))
.CountAsync();
var entries = batchPage.Select(b =>
{
var counts = obsCountLookup.GetValueOrDefault(b.Id, (Active: 0, Superseded: 0));
var hasBeenSuperseded = supersededByLookup.ContainsKey(b.Id);
@@ -86,37 +165,32 @@ public class DigitizationHistoryService : IDigitizationHistoryService
IsCorrection: b.SupersedesBatchId.HasValue,
HasBeenSuperseded: hasBeenSuperseded,
SupersededByBatchId: hasBeenSuperseded ? supersededByBatchId : null,
DraftObservationCount: b.DraftObservations.Count,
DraftObservationCount: b.DraftObservationCount,
LiveObservationCount: counts.Active,
SupersededObservationCount: counts.Superseded,
CreatedAt: b.CreatedAt,
PromotedAt: b.PromotedAt,
PromotionEncounterId: b.PromotionEncounterId,
EnteredByUserId: b.EnteredByUserId,
EnteredByUserName: b.EnteredByUser?.FullName,
EnteredByUserName: b.EnteredByUserName,
VerifiedByUserId: b.VerifiedByUserId,
VerifiedByUserName: b.VerifiedByUser?.FullName,
VerifiedByUserName: b.VerifiedByUserName,
ApprovedByUserId: b.ApprovedByUserId,
ApprovedByUserName: b.ApprovedByUser?.FullName,
AuditTrail: b.Events
.OrderBy(e => e.OccurredAt)
.Select(e => new DigitizationEventSummary(
e.EventType.ToDbString(),
e.OccurredAt,
e.ActorUserId,
e.Actor?.FullName ?? "Unknown",
e.MetadataJson))
.ToList()
ApprovedByUserName: b.ApprovedByUserName,
AuditTrail: auditByBatch.GetValueOrDefault(b.Id, [])
);
}).ToList();
return new PatientDigitizationHistoryResponse(
PatientId: patientId,
TotalBatches: entries.Count,
PromotedBatches: entries.Count(e => e.Status == "PROMOTED"),
SupersededBatches: entries.Count(e => e.HasBeenSuperseded),
PendingBatches: entries.Count(e => e.Status != "PROMOTED" && e.Status != "REJECTED"),
TotalBatches: totalBatches,
PromotedBatches: promotedBatches,
SupersededBatches: supersededBatchCount,
PendingBatches: pendingBatches,
Page: page,
PageSize: pageSize,
TotalPages: totalPages,
Entries: entries
);
}
}
}
@@ -7,6 +7,8 @@ public class DocumentStorageService : IDocumentStorageService
{
private readonly IMinioClient _minio;
private readonly MinioOptions _options;
// Process-lifetime: DocumentStorageService is scoped; bucket only needs ensuring once.
private static int _bucketReady; // 0 = unknown, 1 = ensured
public DocumentStorageService(IMinioClient minio, IOptions<MinioOptions> options)
{
@@ -15,17 +17,21 @@ public class DocumentStorageService : IDocumentStorageService
}
public async Task<(string objectKey, string sha256, long fileSize)> UploadAsync(
Stream fileStream, string contentType, Guid batchId)
Stream fileStream, string contentType, Guid batchId, CancellationToken ct = default)
{
var now = DateTimeOffset.UtcNow;
using var sha256 = SHA256.Create();
using var sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
using var memStream = new MemoryStream();
await fileStream.CopyToAsync(memStream);
memStream.Position = 0;
var buffer = new byte[81920];
int read;
while ((read = await fileStream.ReadAsync(buffer.AsMemory(0, buffer.Length), ct)) > 0)
{
sha256.AppendData(buffer.AsSpan(0, read));
await memStream.WriteAsync(buffer.AsMemory(0, read), ct);
}
var hashBytes = sha256.ComputeHash(memStream);
var hashHex = Convert.ToHexString(hashBytes).ToLowerInvariant();
var hashHex = Convert.ToHexString(sha256.GetHashAndReset()).ToLowerInvariant();
memStream.Position = 0;
var extension = contentType switch
@@ -38,45 +44,49 @@ public class DocumentStorageService : IDocumentStorageService
var objectKey = $"scans/{now.Year}/{now.Month:D2}/{batchId}/{hashHex}.{extension}";
await EnsureBucketAsync();
await EnsureBucketAsync(ct);
await _minio.PutObjectAsync(new PutObjectArgs()
.WithBucket(_options.BucketName)
.WithObject(objectKey)
.WithStreamData(memStream)
.WithObjectSize(memStream.Length)
.WithContentType(contentType));
.WithContentType(contentType), ct);
return (objectKey, hashHex, memStream.Length);
}
public async Task<string> GetPresignedUrlAsync(string objectKey)
public async Task<string> GetPresignedUrlAsync(string objectKey, CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
return await _minio.PresignedGetObjectAsync(new PresignedGetObjectArgs()
.WithBucket(_options.BucketName)
.WithObject(objectKey)
.WithExpiry(_options.PresignedUrlExpiryMinutes * 60));
}
public async Task<Stream> DownloadAsync(string objectKey)
public async Task<Stream> DownloadAsync(string objectKey, CancellationToken ct = default)
{
var memStream = new MemoryStream();
await _minio.GetObjectAsync(new GetObjectArgs()
.WithBucket(_options.BucketName)
.WithObject(objectKey)
.WithCallbackStream(stream => stream.CopyTo(memStream)));
.WithCallbackStream(async (stream, cancellationToken) =>
{
await stream.CopyToAsync(memStream, 81920, cancellationToken);
}), ct);
memStream.Position = 0;
return memStream;
}
public async Task<bool> ObjectExistsAsync(string objectKey)
public async Task<bool> ObjectExistsAsync(string objectKey, CancellationToken ct = default)
{
try
{
await _minio.StatObjectAsync(new StatObjectArgs()
.WithBucket(_options.BucketName)
.WithObject(objectKey));
.WithObject(objectKey), ct);
return true;
}
catch (Minio.Exceptions.ObjectNotFoundException)
@@ -85,10 +95,11 @@ public class DocumentStorageService : IDocumentStorageService
}
}
public async Task EnsureObjectAsync(string objectKey, byte[] content, string contentType)
public async Task EnsureObjectAsync(
string objectKey, byte[] content, string contentType, CancellationToken ct = default)
{
await EnsureBucketAsync();
if (await ObjectExistsAsync(objectKey))
await EnsureBucketAsync(ct);
if (await ObjectExistsAsync(objectKey, ct))
return;
using var stream = new MemoryStream(content);
@@ -97,13 +108,20 @@ public class DocumentStorageService : IDocumentStorageService
.WithObject(objectKey)
.WithStreamData(stream)
.WithObjectSize(stream.Length)
.WithContentType(contentType));
.WithContentType(contentType), ct);
}
private async Task EnsureBucketAsync()
public async Task EnsureBucketAsync(CancellationToken ct = default)
{
var exists = await _minio.BucketExistsAsync(new BucketExistsArgs().WithBucket(_options.BucketName));
if (Interlocked.CompareExchange(ref _bucketReady, 0, 0) == 1)
return;
var exists = await _minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(_options.BucketName), ct);
if (!exists)
await _minio.MakeBucketAsync(new MakeBucketArgs().WithBucket(_options.BucketName));
await _minio.MakeBucketAsync(
new MakeBucketArgs().WithBucket(_options.BucketName), ct);
Interlocked.Exchange(ref _bucketReady, 1);
}
}
}
+85 -26
View File
@@ -145,52 +145,111 @@ public class FhirService : IFhirService
total, count, offset, "Observation");
}
public async Task<Bundle?> GetPatientEverythingAsync(Guid patientId)
public async Task<Bundle?> GetPatientEverythingAsync(
Guid patientId, int count = 100, int offset = 0)
{
count = Math.Clamp(count, 1, 500);
offset = Math.Max(0, offset);
var patient = await _db.Patients.AsNoTracking().FirstOrDefaultAsync(p => p.Id == patientId);
if (patient is null) return null;
var encounters = await _db.Encounters.AsNoTracking()
.Where(e => e.PatientId == patientId)
.ToListAsync();
var observations = await _db.Observations.AsNoTracking()
.Where(o => o.PatientId == patientId)
.OrderByDescending(o => o.RecordedAt)
.ToListAsync();
var encounterCount = await _db.Encounters.AsNoTracking()
.CountAsync(e => e.PatientId == patientId);
var observationCount = await _db.Observations.AsNoTracking()
.CountAsync(o => o.PatientId == patientId);
var total = 1 + encounterCount + observationCount;
var bundle = new Bundle
{
Type = Bundle.BundleType.Searchset,
Total = 1 + encounters.Count + observations.Count,
Total = total,
Meta = new Meta { LastUpdated = DateTimeOffset.UtcNow },
};
bundle.Entry.Add(new Bundle.EntryComponent
{
FullUrl = $"{_options.BaseUrl}/Patient/{patient.Id}",
Resource = PatientMapper.ToFhir(patient, _options.BaseUrl),
Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Match },
});
// Virtual layout: index 0 = Patient, then encounters, then observations.
var remaining = count;
var cursor = offset;
foreach (var enc in encounters)
if (cursor == 0 && remaining > 0)
{
bundle.Entry.Add(new Bundle.EntryComponent
{
FullUrl = $"{_options.BaseUrl}/Encounter/{enc.Id}",
Resource = EncounterMapper.ToFhir(enc, _options.BaseUrl),
Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include },
FullUrl = $"{_options.BaseUrl}/Patient/{patient.Id}",
Resource = PatientMapper.ToFhir(patient, _options.BaseUrl),
Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Match },
});
remaining--;
cursor = 1;
}
foreach (var obs in observations)
if (remaining > 0 && cursor < 1 + encounterCount)
{
bundle.Entry.Add(new Bundle.EntryComponent
var encSkip = Math.Max(0, cursor - 1);
var encTake = Math.Min(remaining, encounterCount - encSkip);
if (encTake > 0)
{
FullUrl = $"{_options.BaseUrl}/Observation/{obs.Id}",
Resource = ObservationMapper.ToFhir(obs, _options.BaseUrl),
Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include },
});
var encounters = await _db.Encounters.AsNoTracking()
.Where(e => e.PatientId == patientId)
.OrderByDescending(e => e.AdmissionDate)
.Skip(encSkip)
.Take(encTake)
.ToListAsync();
foreach (var enc in encounters)
{
bundle.Entry.Add(new Bundle.EntryComponent
{
FullUrl = $"{_options.BaseUrl}/Encounter/{enc.Id}",
Resource = EncounterMapper.ToFhir(enc, _options.BaseUrl),
Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include },
});
}
remaining -= encounters.Count;
cursor += encounters.Count;
}
}
if (remaining > 0 && cursor < total)
{
var obsSkip = Math.Max(0, cursor - 1 - encounterCount);
var obsTake = Math.Min(remaining, observationCount - obsSkip);
if (obsTake > 0)
{
var observations = await _db.Observations.AsNoTracking()
.Where(o => o.PatientId == patientId)
.OrderByDescending(o => o.RecordedAt)
.Skip(obsSkip)
.Take(obsTake)
.ToListAsync();
foreach (var obs in observations)
{
bundle.Entry.Add(new Bundle.EntryComponent
{
FullUrl = $"{_options.BaseUrl}/Observation/{obs.Id}",
Resource = ObservationMapper.ToFhir(obs, _options.BaseUrl),
Search = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include },
});
}
}
}
var selfUrl = $"{_options.BaseUrl}/Patient/{patientId}/$everything?_count={count}&_offset={offset}";
bundle.Link.Add(new Bundle.LinkComponent { Relation = "self", Url = selfUrl });
if (offset + count < total)
{
var nextUrl = $"{_options.BaseUrl}/Patient/{patientId}/$everything?_count={count}&_offset={offset + count}";
bundle.Link.Add(new Bundle.LinkComponent { Relation = "next", Url = nextUrl });
}
if (offset > 0)
{
var prevOffset = Math.Max(0, offset - count);
var prevUrl = $"{_options.BaseUrl}/Patient/{patientId}/$everything?_count={count}&_offset={prevOffset}";
bundle.Link.Add(new Bundle.LinkComponent { Relation = "previous", Url = prevUrl });
}
return bundle;
@@ -1,4 +1,5 @@
public interface IDigitizationHistoryService
{
Task<PatientDigitizationHistoryResponse> GetPatientHistoryAsync(Guid patientId);
}
Task<PatientDigitizationHistoryResponse> GetPatientHistoryAsync(
Guid patientId, int page = 1, int pageSize = 20);
}
@@ -1,10 +1,13 @@
public interface IDocumentStorageService
{
Task<(string objectKey, string sha256, long fileSize)> UploadAsync(Stream fileStream, string contentType, Guid batchId);
Task<string> GetPresignedUrlAsync(string objectKey);
Task<Stream> DownloadAsync(string objectKey);
Task<(string objectKey, string sha256, long fileSize)> UploadAsync(
Stream fileStream, string contentType, Guid batchId, CancellationToken ct = default);
Task<string> GetPresignedUrlAsync(string objectKey, CancellationToken ct = default);
Task<Stream> DownloadAsync(string objectKey, CancellationToken ct = default);
/// <summary>Returns false when the object is missing from the bucket.</summary>
Task<bool> ObjectExistsAsync(string objectKey);
Task<bool> ObjectExistsAsync(string objectKey, CancellationToken ct = default);
/// <summary>Uploads bytes only when the object key is not already present.</summary>
Task EnsureObjectAsync(string objectKey, byte[] content, string contentType);
}
Task EnsureObjectAsync(string objectKey, byte[] content, string contentType, CancellationToken ct = default);
/// <summary>Ensures the configured bucket exists. Safe to call repeatedly; caches success in-process.</summary>
Task EnsureBucketAsync(CancellationToken ct = default);
}
@@ -16,7 +16,7 @@ public interface IFhirService
string? patient, string? code, string? date,
string? category, string? encounter, int count, int offset);
Task<Bundle?> GetPatientEverythingAsync(Guid patientId);
Task<Bundle?> GetPatientEverythingAsync(Guid patientId, int count = 100, int offset = 0);
CapabilityStatement GetCapabilityStatement();
}
@@ -1,4 +1,5 @@
public interface IOcrService
{
Task<OcrExtractionResult> ExtractAsync(Stream documentStream, string contentType);
}
Task<OcrExtractionResult> ExtractAsync(
Stream documentStream, string contentType, CancellationToken ct = default);
}
@@ -21,5 +21,6 @@ public interface IPromotionService
/// </summary>
Task<PromotionResultResponse> GetPromotionResultAsync(Guid batchId);
Task<PromotionResult> PromoteAsync(Guid batchId, Guid actorUserId);
Task<PromotionResult> PromoteAsync(
Guid batchId, Guid actorUserId, CancellationToken ct = default);
}
@@ -1,6 +1,5 @@
using Azure;
using Azure.AI.DocumentIntelligence;
using Microsoft.Extensions.Options;
public class AzureDocumentOcrService : IOcrService
{
@@ -56,26 +55,24 @@ public class AzureDocumentOcrService : IOcrService
private readonly ILogger<AzureDocumentOcrService> _logger;
public AzureDocumentOcrService(
IOptions<OcrOptions> options,
DocumentIntelligenceClient client,
ILogger<AzureDocumentOcrService> logger)
{
var opts = options.Value.Azure;
_client = new DocumentIntelligenceClient(
new Uri(opts.Endpoint),
new AzureKeyCredential(opts.ApiKey));
_client = client;
_logger = logger;
}
public async Task<OcrExtractionResult> ExtractAsync(
Stream documentStream, string contentType)
Stream documentStream, string contentType, CancellationToken ct = default)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var content = BinaryData.FromStream(documentStream);
var content = await BinaryData.FromStreamAsync(documentStream, ct);
var operation = await _client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-document",
content);
content,
cancellationToken: ct);
var result = operation.Value;
var fields = new List<OcrExtractedField>();
@@ -10,18 +10,20 @@ public class ImagePreprocessor
private const int PdfRenderWidth = 2550;
private const int PdfRenderHeight = 3300;
public Stream Preprocess(Stream input, string contentType)
public async Task<Stream> PreprocessAsync(
Stream input, string contentType, CancellationToken ct = default)
{
Stream? pdfRenderStream = null;
try
{
if (contentType == "application/pdf")
{
pdfRenderStream = RenderPdfFirstPage(input);
pdfRenderStream = await RenderPdfFirstPageAsync(input, ct);
input = pdfRenderStream;
}
using var image = Image.Load(input);
ct.ThrowIfCancellationRequested();
using var image = await Image.LoadAsync(input, ct);
image.Mutate(ctx => ctx
.Grayscale()
@@ -29,22 +31,26 @@ public class ImagePreprocessor
.BinaryThreshold(0.5f));
var output = new MemoryStream();
image.SaveAsPng(output);
await image.SaveAsPngAsync(output, ct);
output.Position = 0;
return output;
}
finally
{
pdfRenderStream?.Dispose();
if (pdfRenderStream is not null)
await pdfRenderStream.DisposeAsync();
}
}
private static Stream RenderPdfFirstPage(Stream pdfStream)
private static async Task<Stream> RenderPdfFirstPageAsync(
Stream pdfStream, CancellationToken ct)
{
using var buffer = new MemoryStream();
pdfStream.CopyTo(buffer);
await pdfStream.CopyToAsync(buffer, 81920, ct);
var pdfBytes = buffer.ToArray();
ct.ThrowIfCancellationRequested();
using var docReader = DocLib.Instance.GetDocReader(
pdfBytes,
new PageDimensions(PdfRenderWidth, PdfRenderHeight));
@@ -59,7 +65,7 @@ public class ImagePreprocessor
using var image = Image.LoadPixelData<Bgra32>(rawBytes, width, height);
var output = new MemoryStream();
image.SaveAsPng(output);
await image.SaveAsPngAsync(output, ct);
output.Position = 0;
return output;
}
@@ -37,8 +37,12 @@ public class OcrDraftPreFiller
}
public async Task PreFillAsync(
Guid batchId, BatchType batchType, OcrExtractionResult extraction)
Guid batchId,
BatchType batchType,
OcrExtractionResult extraction,
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var requirements = BatchTypeFieldRequirements.ForBatchType(batchType);
var confidentFields = extraction.Fields
.Where(f => f.Confidence >= _options.ConfidenceThreshold)
@@ -54,7 +58,7 @@ public class OcrDraftPreFiller
if (requirements.ShowObservations)
await PreFillObservationsAsync(batchId, confidentFields);
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(ct);
}
private async Task PreFillPatientAsync(
@@ -2,7 +2,7 @@ using System.Text.RegularExpressions;
using Microsoft.Extensions.Options;
using Tesseract;
public class TesseractOcrService : IOcrService
public class TesseractOcrService : IOcrService, IDisposable
{
private static readonly (Regex Pattern, string FieldName)[] ClinicalPatterns =
[
@@ -25,6 +25,9 @@ public class TesseractOcrService : IOcrService
private readonly TesseractOcrOptions _options;
private readonly ImagePreprocessor _preprocessor;
private readonly ILogger<TesseractOcrService> _logger;
private readonly object _engineLock = new();
private TesseractEngine? _engine;
private bool _disposed;
public TesseractOcrService(
IOptions<OcrOptions> options,
@@ -37,28 +40,57 @@ public class TesseractOcrService : IOcrService
}
public async Task<OcrExtractionResult> ExtractAsync(
Stream documentStream, string contentType)
Stream documentStream, string contentType, CancellationToken ct = default)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
using var preprocessed = _preprocessor.Preprocess(documentStream, contentType);
using var memStream = new MemoryStream();
await preprocessed.CopyToAsync(memStream);
var imageBytes = memStream.ToArray();
await using var preprocessed = await _preprocessor.PreprocessAsync(
documentStream, contentType, ct);
using var engine = new TesseractEngine(
_options.DataPath, _options.Language, EngineMode.Default);
using var pix = Pix.LoadFromMemory(imageBytes);
using var page = engine.Process(pix);
ct.ThrowIfCancellationRequested();
byte[] imageBytes;
if (preprocessed is MemoryStream ms)
{
imageBytes = ms.ToArray();
}
else
{
using var copy = new MemoryStream();
await preprocessed.CopyToAsync(copy, ct);
imageBytes = copy.ToArray();
}
ct.ThrowIfCancellationRequested();
string rawText;
float meanConfidence;
lock (_engineLock)
{
var engine = GetEngine();
using var pix = Pix.LoadFromMemory(imageBytes);
using var page = engine.Process(pix);
rawText = page.GetText();
meanConfidence = page.GetMeanConfidence();
}
var rawText = page.GetText();
var meanConfidence = page.GetMeanConfidence();
var fields = ParseClinicalText(rawText, meanConfidence);
sw.Stop();
_logger.LogDebug(
"Tesseract OCR finished in {DurationMs}ms with {FieldCount} fields",
sw.ElapsedMilliseconds, fields.Count);
return new OcrExtractionResult(fields, rawText, (int)sw.ElapsedMilliseconds);
}
private TesseractEngine GetEngine()
{
ObjectDisposedException.ThrowIf(_disposed, this);
return _engine ??= new TesseractEngine(
_options.DataPath, _options.Language, EngineMode.Default);
}
private static List<OcrExtractedField> ParseClinicalText(string text, float meanConfidence)
{
var fields = new List<OcrExtractedField>();
@@ -87,4 +119,13 @@ public class TesseractOcrService : IOcrService
return fields;
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_engine?.Dispose();
_engine = null;
}
}
@@ -138,6 +138,7 @@ public class PromotionService : IPromotionService
public async Task<PromotionResultResponse> GetPromotionResultAsync(Guid batchId)
{
var batch = await _db.DigitizationBatches
.AsNoTracking()
.FirstOrDefaultAsync(b => b.Id == batchId);
if (batch is null)
@@ -150,6 +151,7 @@ public class PromotionService : IPromotionService
// Retrieve the live patient by looking up the encounter
var encounter = await _db.Encounters
.AsNoTracking()
.Include(e => e.Patient)
.FirstOrDefaultAsync(e => e.Id == batch.PromotionEncounterId);
@@ -159,6 +161,7 @@ public class PromotionService : IPromotionService
"PROMOTION_ENCOUNTER_NOT_FOUND");
var observationIds = await _db.Observations
.AsNoTracking()
.Where(o => o.SourceBatchId == batchId)
.Select(o => o.Id)
.ToArrayAsync();
@@ -324,8 +327,10 @@ public class PromotionService : IPromotionService
if (draft.DateOfBirth.HasValue)
{
var sameDobPatients = await _db.Patients
.AsNoTracking()
.Where(p => p.DateOfBirth == draft.DateOfBirth)
.Select(p => new { p.Id, p.Mrn, p.FullName })
.Take(50)
.ToListAsync();
foreach (var candidate in sameDobPatients)
@@ -603,13 +608,14 @@ public class PromotionService : IPromotionService
return Task.FromResult((observationIds.ToArray(), outboxCount));
}
public async Task<PromotionResult> PromoteAsync(Guid batchId, Guid actorUserId)
public async Task<PromotionResult> PromoteAsync(
Guid batchId, Guid actorUserId, CancellationToken ct = default)
{
var stopwatch = Stopwatch.StartNew();
try
{
await using var transaction = await _db.Database.BeginTransactionAsync();
await using var transaction = await _db.Database.BeginTransactionAsync(ct);
try
{
@@ -617,7 +623,7 @@ public class PromotionService : IPromotionService
.Include(b => b.DraftPatient)
.Include(b => b.DraftEncounter)
.Include(b => b.DraftObservations)
.FirstOrDefaultAsync(b => b.Id == batchId);
.FirstOrDefaultAsync(b => b.Id == batchId, ct);
if (batch is null)
throw new NotFoundException("Batch not found.", "BATCH_NOT_FOUND");
@@ -635,8 +641,8 @@ public class PromotionService : IPromotionService
var core = await ExecutePromotionCoreAsync(
batch, actorUserId, enableRetroactiveAlerts, now);
await _db.SaveChangesAsync();
await transaction.CommitAsync();
await _db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
stopwatch.Stop();
DiagnosticsMetrics.PromotionDuration.Observe(stopwatch.Elapsed.TotalSeconds);
@@ -15,6 +15,7 @@ public class UserDirectoryService : IUserDirectoryService
return await query
.OrderBy(u => u.FullName)
.Take(500)
.Select(u => new UserSummaryResponse(
u.Id,
u.Username,
@@ -28,7 +28,6 @@ public class VerificationService : IVerificationService
Guid batchId, VerifyBatchRequest request, Guid verifierUserId)
{
var batch = await _db.DigitizationBatches
.Include(b => b.Events)
.FirstOrDefaultAsync(b => b.Id == batchId);
if (batch is null)
@@ -79,6 +79,9 @@ public class WorkQueueService : IWorkQueueService
string sortBy,
string sortDirection)
{
pageSize = Math.Clamp(pageSize, 1, 100);
page = Math.Max(1, page);
if (!_allowedSortFields.Contains(sortBy))
throw new ValidationException(
$"Invalid sortBy field '{sortBy}'. Allowed: {string.Join(", ", _allowedSortFields)}.",
@@ -87,10 +90,8 @@ public class WorkQueueService : IWorkQueueService
var totalCount = await query.CountAsync();
var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
var sorted = ApplySort(query, sortBy, sortDirection);
var sorted = ApplySort(query.AsNoTracking(), sortBy, sortDirection);
var items = await sorted
.Include(b => b.EnteredByUser)
.Include(b => b.Events)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(b => new WorkQueueItemResponse(
@@ -128,23 +129,21 @@ public class WorkQueueService : IWorkQueueService
statusCounts[status.ToDbString()] = count;
}
var pendingBatches = await _db.DigitizationBatches
var pendingQuery = _db.DigitizationBatches
.AsNoTracking()
.Where(b => b.Status == BatchStatus.PendingVerification)
.Select(b => b.UpdatedAt)
.ToListAsync();
.Where(b => b.Status == BatchStatus.PendingVerification);
var pendingCount = await pendingQuery.CountAsync();
double avgTimeInQueueMinutes = 0;
double oldestPendingMinutes = 0;
if (pendingBatches.Count > 0)
if (pendingCount > 0)
{
var ages = pendingBatches
.Select(updatedAt => (now - updatedAt).TotalMinutes)
.ToList();
avgTimeInQueueMinutes = ages.Average();
oldestPendingMinutes = ages.Max();
var oldestUpdatedAt = await pendingQuery.MinAsync(b => b.UpdatedAt);
oldestPendingMinutes = (now - oldestUpdatedAt).TotalMinutes;
avgTimeInQueueMinutes = await pendingQuery
.Select(b => (now - b.UpdatedAt).TotalMinutes)
.AverageAsync();
}
var cutoff = now.AddHours(-24);
@@ -177,7 +176,7 @@ public class WorkQueueService : IWorkQueueService
_logger.LogDebug(
"Work queue overview: {PendingCount} pending, avg queue {AvgMinutes:F1}m, reject rate {RejectRate:P1}",
pendingBatches.Count, avgTimeInQueueMinutes, rejectRate);
pendingCount, avgTimeInQueueMinutes, rejectRate);
return new WorkQueueOverviewResponse
{