Files
vigilcare-clinical/VigilCareClinicalAPI/BackgroundServices/PatientPhiMigrationService.cs
T
Trent 68a2ab3204
CI / changes (push) Successful in 17s
CI / frontend (push) Skipped
CI / backend (push) Successful in 15m10s
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.
2026-11-30 21:32:43 +08:00

68 lines
2.0 KiB
C#

using Microsoft.EntityFrameworkCore;
public class PatientPhiMigrationService : IHostedService
{
private const int BatchSize = 500;
private readonly IServiceProvider _services;
private readonly ILogger<PatientPhiMigrationService> _logger;
public PatientPhiMigrationService(
IServiceProvider services,
ILogger<PatientPhiMigrationService> logger)
{
_services = services;
_logger = logger;
}
public async Task StartAsync(CancellationToken ct)
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var crypto = scope.ServiceProvider.GetRequiredService<IPhiEncryptionService>();
var totalMigrated = 0;
Guid? afterId = null;
while (!ct.IsCancellationRequested)
{
IQueryable<Patient> query = db.Patients.OrderBy(p => p.Id);
if (afterId is Guid cursor)
query = query.Where(p => p.Id.CompareTo(cursor) > 0);
var batch = await query.Take(BatchSize).ToListAsync(ct);
if (batch.Count == 0)
break;
afterId = batch[^1].Id;
var migrated = 0;
foreach (var patient in batch)
{
if (patient.NameSearchToken is not null && crypto.IsEncrypted(patient.FirstName))
continue;
patient.NameSearchToken = crypto.ComputeNameSearchToken(
patient.FirstName, patient.LastName);
migrated++;
}
if (migrated > 0)
{
await db.SaveChangesAsync(ct);
totalMigrated += migrated;
}
db.ChangeTracker.Clear();
}
if (totalMigrated > 0)
{
_logger.LogInformation(
"PHI migration: updated {Count} patient search tokens", totalMigrated);
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}