using System.Text;
using Microsoft.EntityFrameworkCore;
///
/// Ensures demo/seeded batches have ScannedDocument rows and placeholder PDF
/// objects in MinIO so workstation document viewing does not 500.
/// Idempotent — safe to run on every bootstrap.
///
public static class SeedDocumentStorage
{
/// Minimal valid single-page PDF used as a seed placeholder.
public static readonly byte[] MinimalPdf = Encoding.ASCII.GetBytes(
"%PDF-1.4\n" +
"1 0 obj<>endobj\n" +
"2 0 obj<>endobj\n" +
"3 0 obj<>endobj\n" +
"xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n0000000052 00000 n \n0000000101 00000 n \n" +
"trailer<>\nstartxref\n178\n%%EOF\n");
public static async Task EnsureAsync(
AppDbContext db,
IDocumentStorageService storage,
ILogger logger,
CancellationToken ct = default)
{
var batches = await db.DigitizationBatches
.AsNoTracking()
.Where(b => b.DocumentRef != "live-capture" && b.DocumentRef != "")
.Select(b => new { b.Id, b.DocumentRef, b.DocumentSha256 })
.ToListAsync(ct);
if (batches.Count == 0)
return;
var batchIds = batches.Select(b => b.Id).ToList();
var existingDocBatchIds = await db.ScannedDocuments
.AsNoTracking()
.Where(d => batchIds.Contains(d.BatchId))
.Select(d => d.BatchId)
.ToListAsync(ct);
var existingSet = existingDocBatchIds.ToHashSet();
var missingDocs = batches
.Where(b => !existingSet.Contains(b.Id))
.Select(b => new ScannedDocument
{
Id = Guid.NewGuid(),
BatchId = b.Id,
ObjectKey = b.DocumentRef,
Sha256 = NormalizeSha(b.DocumentSha256),
ContentType = "application/pdf",
FileSizeBytes = MinimalPdf.Length,
UploadedAt = DateTimeOffset.UtcNow,
})
.ToList();
if (missingDocs.Count > 0)
{
db.ScannedDocuments.AddRange(missingDocs);
await db.SaveChangesAsync(ct);
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 objectKey in keysToEnsure)
{
ct.ThrowIfCancellationRequested();
if (!await storage.ObjectExistsAsync(objectKey, ct))
{
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);
}
private static string NormalizeSha(string? sha)
{
if (string.IsNullOrWhiteSpace(sha))
return new string('0', 64);
return sha.Length >= 64 ? sha[..64] : sha.PadRight(64, '0');
}
}