< Summary

Information
Class: Anichron.Core.Data.AnichronDbContext
Assembly: Anichron.Core
File(s): /home/runner/work/anichron/anichron/src/Anichron.Core/Data/AnichronDbContext.cs
Tag: 19_45211875487
Line coverage
98%
Covered lines: 458
Uncovered lines: 5
Coverable lines: 463
Total lines: 494
Line coverage: 98.9%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_Users()100%11100%
get_StorageConfigs()100%11100%
get_MediaAssets()100%11100%
get_Metadata()100%11100%
get_ProxyFiles()100%11100%
get_Bursts()100%11100%
get_BurstChecks()100%11100%
get_Interactions()100%11100%
get_RefreshTokens()100%11100%
get_Invites()100%11100%
get_WorkItems()100%11100%
get_ProxyOrphans()100%11100%
ExecuteInTransactionAsync()100%210%
OnModelCreating(...)100%11100%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.Core/Data/AnichronDbContext.cs

#LineLine coverage
 1using Anichron.Core.Domain;
 2using Microsoft.EntityFrameworkCore;
 3using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
 4
 5namespace Anichron.Core.Data;
 6
 13087public class AnichronDbContext(DbContextOptions<AnichronDbContext> options) : DbContext(options), IUnitOfWork
 8{
 9    private const string identityNormalizedComment =
 10        "Always stored trimmed and lowercased: an EF value converter applies "
 11        + "IdentityNormalizer.Normalize on every write and to every equality comparison against "
 12        + "this column, so the case-sensitive unique index cannot hold two spellings of one name.";
 13
 15414    public DbSet<User> Users => Set<User>();
 23715    public DbSet<UserStorageConfig> StorageConfigs => Set<UserStorageConfig>();
 86216    public DbSet<MediaAsset> MediaAssets => Set<MediaAsset>();
 1517    public DbSet<Metadata> Metadata => Set<Metadata>();
 12018    public DbSet<ProxyFile> ProxyFiles => Set<ProxyFile>();
 25919    public DbSet<Burst> Bursts => Set<Burst>();
 85620    public DbSet<BurstCheck> BurstChecks => Set<BurstCheck>();
 20521    public DbSet<AssetInteraction> Interactions => Set<AssetInteraction>();
 1322    public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
 1123    public DbSet<Invite> Invites => Set<Invite>();
 10424    public DbSet<WorkItem> WorkItems => Set<WorkItem>();
 3125    public DbSet<ProxyOrphan> ProxyOrphans => Set<ProxyOrphan>();
 26
 27    // Stryker disable all
 28    public async Task ExecuteInTransactionAsync(Func<Task> action, CancellationToken ct = default)
 029    {
 030        await using var tx = await Database.BeginTransactionAsync(ct);
 031        await action();
 032        await tx.CommitAsync(ct);
 033    }
 34
 35    protected override void OnModelCreating(ModelBuilder modelBuilder)
 6836    {
 37        // Stryker disable once Statement
 6838        base.OnModelCreating(modelBuilder);
 39
 6840        modelBuilder.Entity<AssetInteraction>(entity =>
 6841        {
 6842            entity.ToTable(t => t.HasComment(
 6843                    "Per-user state for one asset. Never shared between users: two people looking at "
 6844                    + "the same file each get their own row. Drives flashback weighting — hidden "
 6845                    + "excludes, starred always includes and sorts first, liked raises DisplayWeight."
 6846                ));
 6847            entity.Property(i => i.HiddenAt).HasComment(
 6848                "When the user last hid the asset; NULL while it is shown. Orders the user's hidden memories, "
 6849                + "newest first.");
 6850            entity.HasIndex(i => new { i.UserId, i.AssetId }).IsUnique().HasDatabaseName(InteractionIndexNames.OnePerUse
 6851            entity.HasQueryFilter(i => !i.Asset.IsSoftDeleted);
 6852        });
 53
 6854        modelBuilder.Entity<Burst>(entity =>
 6855        {
 6856            entity.ToTable(t => t.HasComment(
 6857                    "Groups photos of one storage config taken moments apart, so a flashback shows one "
 6858                    + "memory rather than nine near-identical frames. Written only by the Worker's "
 6859                    + "BurstDetection work item, which also repairs bursts: one left with fewer than two "
 6860                    + "active members is deleted, and so is one with no members at all."
 6861                ));
 6862            entity.Property(b => b.PrimaryAssetId).HasComment(
 6863                "The stored cover, the earliest member. SetNull on delete, so deleting the cover's row "
 6864                + "(a storage config removal cascading to its assets) cannot fail on the burst; the "
 6865                + "next BurstDetection run picks a new cover or deletes the burst.");
 6866
 6867            entity.HasOne(b => b.PrimaryAsset)
 6868                .WithMany()
 6869                .HasForeignKey(b => b.PrimaryAssetId)
 6870                .OnDelete(DeleteBehavior.SetNull);
 6871            entity.HasQueryFilter(b => b.PrimaryAssetId == null || !b.PrimaryAsset!.IsSoftDeleted);
 6872        });
 73
 6874        modelBuilder.Entity<BurstCheck>(entity =>
 6875        {
 6876            entity.ToTable(t => t.HasComment(
 6877                    "One row per photo burst detection has checked; no row means unchecked. Owned by the "
 6878                    + "BurstDetection work item, which reads the original once when it checks a photo. "
 6879                    + "A file edited in place loses its row, so it is checked again."
 6880                ));
 6881            entity.Property(c => c.IsCandidate).HasComment(
 6882                "The photo has an EXIF capture time, a camera make and model, and a thumbnail; only "
 6883                + "candidates are grouped. False also when the original could not be read.");
 6884            entity.Property(c => c.CameraBurstId).HasComment(
 6885                "Apple's BurstUUID from the original's maker note: photos of one storage config "
 6886                + "sharing it form one burst. Null when the camera wrote none.");
 6887            entity.HasKey(c => c.AssetId);
 6888
 6889            entity.HasOne(c => c.Asset)
 6890                  .WithOne()
 6891                  .HasForeignKey<BurstCheck>(c => c.AssetId)
 6892                  .OnDelete(DeleteBehavior.Cascade);
 6893            entity.HasIndex(c => c.CameraBurstId);
 6894            entity.HasQueryFilter(c => !c.Asset.IsSoftDeleted);
 6895        });
 96
 6897        modelBuilder.Entity<MediaAsset>(entity =>
 6898        {
 6899            entity.ToTable(t => t.HasComment(
 68100                    "One row per media file, scoped to a storage config. Written ONLY by the Worker — "
 68101                    + "the API never writes media data."
 68102                ));
 68103            entity.Property(m => m.ContentHash).HasComment(
 68104                "XXHash64 of the file contents. Dedup is deliberately CONFIG-SCOPED: the same "
 68105                + "bytes under two storage configs are two assets, which is what makes multi-user "
 68106                + "work. A global unique index on this column alone would break that and must "
 68107                + "never be added.");
 68108            entity.Property(m => m.FilePath).HasComment(
 68109                "Path relative to the storage config root. Not to be confused with "
 68110                + "ProxyFiles.ProxyPath, which is relative to the proxy root.");
 68111            entity.Property(m => m.DateCaptured).HasComment(
 68112                "The wall-clock time the file records it was captured. NULL when it records none: the asset "
 68113                + "is undated, never dated by the file's last-modified time, and is left out of On This Day "
 68114                + "and burst detection (ADR 0015).");
 68115            entity.Ignore(m => m.Captured);
 68116            entity.Property(m => m.CaptureOffset)
 68117                  .HasConversion(new ValueConverter<Offset, int>(offset => offset.Seconds, seconds => Offset.FromSeconds
 68118                  .HasComment(
 68119                      "Seconds east of UTC that the file records with DateCaptured; NULL when it records none. "
 68120                      + "Kept as recorded, even when it disagrees with CaptureZone (ADR 0015).");
 68121            entity.Property(m => m.CaptureSource).HasConversion<string>().HasComment(
 68122                "Which kind of source DateCaptured came from; NULL exactly when DateCaptured is.");
 68123            entity.Property(m => m.CaptureZone).HasComment(
 68124                "IANA time zone at the asset's position when it was ingested, looked up offline; NULL without "
 68125                + "a position. Never changes DateCaptured or CaptureOffset.");
 68126            entity.Property(m => m.Month).HasComment(
 68127                "Stored apart from DateCaptured so \"On This Day\" is an index lookup on "
 68128                + "(Month, Day) rather than an EXTRACT() scan over every row.");
 68129            entity.Property(m => m.Day).HasComment(
 68130                "See Month — the pair backs IX_MediaAsset_Flashback.");
 68131            entity.Property(m => m.PairedAssetId).HasComment(
 68132                "Live Photo pairing: the photo points at its video. The video is part of the photo, never a "
 68133                + "memory of its own, and has at most one photo (unique): pairing hands it over, reconciliation "
 68134                + "soft-deletes it with its photo and leaves a lone copy of it alone. Without its video the photo "
 68135                + "is shown as a still photo, so SetNull on delete.");
 68136            entity.Property(m => m.IsLivePhotoVideo).HasComment(
 68137                "Whether the row is a Live Photo's video: set when a photo is paired with it, never cleared, even "
 68138                + "when the photo lets go of it or is purged. Pairing soft-deletes a video its photo lets go of, and "
 68139                + "a flagged video crawled alone follows only its photo, so it is never a memory of its own (ADR 0019)."
 68140            entity.Property(m => m.IsSoftDeleted).HasComment(
 68141                "Set by reconciliation when a complete crawl did not find the file, or when its path "
 68142                + "now holds content stored at another path. Soft rather than hard so the user's "
 68143                + "interactions survive, and a crawl that finds the file again clears it (auto-restore).");
 68144
 68145            // Composite Index for "On This Day" (Optimized for Flashbacks)
 68146            entity.HasIndex(m => new { m.Month, m.Day }).HasDatabaseName("IX_MediaAsset_Flashback");
 68147
 68148            // One active asset per (config, hash)
 68149            entity.HasIndex(m => new { m.StorageConfigId, m.ContentHash }, MediaAssetIndexNames.ActiveContentHashUnique)
 68150                  .IsUnique()
 68151                  .HasFilter(@"""IsSoftDeleted"" = false");
 68152
 68153            entity.HasIndex(m => new { m.StorageConfigId, m.ContentHash }, MediaAssetIndexNames.SoftDeletedContentHash)
 68154                  .HasFilter(@"""IsSoftDeleted"" = true");
 68155
 68156            // Unique Constraint: One file path per storage config
 68157            entity.HasIndex(m => new { m.StorageConfigId, m.FilePath })
 68158                  .IsUnique()
 68159                  .HasDatabaseName(MediaAssetIndexNames.FilePathUnique);
 68160
 68161            entity.HasIndex(m => new { m.StorageConfigId, m.DateCaptured });
 68162
 68163            entity.HasIndex(m => m.PairedAssetId)
 68164                  .IsUnique()
 68165                  .HasDatabaseName(MediaAssetIndexNames.PairedAssetIdUnique);
 68166
 68167            // Self-Reference (Paired Asset)
 68168            entity.HasOne(m => m.PairedAsset)
 68169                  .WithMany()
 68170                  .HasForeignKey(m => m.PairedAssetId)
 68171                  .OnDelete(DeleteBehavior.SetNull);
 68172
 68173            // N:1 with Burst
 68174            entity.HasOne(m => m.Burst)
 68175                  .WithMany(b => b.Assets)
 68176                  .HasForeignKey(m => m.BurstId)
 68177                  .OnDelete(DeleteBehavior.SetNull); // Keeping the photo if the burst is dissolved
 68178
 68179            // 1:N with ProxyFiles
 68180            // Stryker disable once Statement
 68181            entity.HasMany(m => m.ProxyFiles)
 68182                  .WithOne(p => p.Asset)
 68183                  .HasForeignKey(p => p.AssetId)
 68184                  .OnDelete(DeleteBehavior.Cascade);
 68185
 68186            // 1:N with Interactions
 68187            // Stryker disable once Statement
 68188            entity.HasMany(m => m.Interactions)
 68189                  .WithOne(i => i.Asset)
 68190                  .HasForeignKey(i => i.AssetId);
 68191
 68192            // Partial index covering only active (non-deleted) assets
 68193            entity.HasIndex(m => m.IsSoftDeleted)
 68194                  .HasFilter(@"""IsSoftDeleted"" = false")
 68195                  .HasDatabaseName("IX_MediaAssets_Active");
 68196
 68197            // Global Query Filter: Hide soft-deleted files by default
 68198            entity.HasQueryFilter(m => !m.IsSoftDeleted);
 68199
 68200            // Enum Conversion
 68201            entity.Property(m => m.MediaType).HasConversion<string>();
 68202        });
 203
 68204        modelBuilder.Entity<Metadata>(entity =>
 68205        {
 68206            entity.ToTable(t => t.HasComment(
 68207                    "What a file records in its EXIF, XMP, IPTC, QuickTime or AVI metadata, 1:1 with MediaAsset and "
 68208                    + "keyed by it — there is no separate Id. Populated by MetadataExtractionMiddleware; every field "
 68209                    + "is best-effort, because a file may record none of it."
 68210                ));
 68211            entity.OwnsOne(m => m.Description, description => description.Property(d => d.Orientation)
 68212                  .HasDefaultValue(ExifOrientation.Upright)
 68213                  .HasComment(
 68214                      "EXIF orientation value, 1-8 (1 = upright, also used when absent or invalid): "
 68215                      + "from the container's irot for a HEIC, the video track's rotation for a video, "
 68216                      + "and the EXIF tag otherwise. Kept as an EXIF value because 5 and 7 combine a "
 68217                      + "rotation with a mirror and cannot be expressed as degrees; a reader converts, "
 68218                      + "and for 5-8 swaps Width/Height. Proxies are already upright and a video's "
 68219                      + "player applies its own rotation, so rotate neither by it."));
 68220            entity.Property(m => m.Blurhash).HasComment(
 68221                "BlurHash placeholder string (4x3 components), computed by the Worker from the "
 68222                + "upright image. Kept here rather than as a proxy file so a response needs no disk "
 68223                + "read for it. A video's is computed from its poster. Null for assets ingested "
 68224                + "before the column existed, which are not backfilled.");
 68225            entity.HasKey(m => m.AssetId);
 68226
 68227            // 1:1 with MediaAsset
 68228            // Stryker disable once Statement
 68229            entity.HasOne(m => m.Asset)
 68230                  .WithOne(a => a.Metadata)
 68231                  .HasForeignKey<Metadata>(m => m.AssetId)
 68232                  .OnDelete(DeleteBehavior.Cascade);
 68233            entity.HasQueryFilter(e => !e.Asset.IsSoftDeleted);
 68234        });
 235
 68236        modelBuilder.Entity<ProxyFile>(entity =>
 68237        {
 68238            entity.ToTable(t => t.HasComment(
 68239                    "One row per generated artefact on the local SSD. An asset has several, but at "
 68240                    + "most one per ProxyType, so of two attempts racing to add the same proxy only one "
 68241                    + "row lands. Written only by ProxyStagingWriter, at the moment the file reaches "
 68242                    + "its final name."
 68243                ));
 68244            entity.Property(p => p.ProxyPath).HasComment(
 68245                "Path relative to the proxy root, sharded by CONTENT rather than by ingestion "
 68246                + "attempt so a retry overwrites its own debris instead of stranding it. "
 68247                + "IProxyDirectoryStrategy is the single place that rule lives.");
 68248            entity.Property(p => p.ProxyType).HasComment(
 68249                "Thumbnail, WebVideo, FullPreview or CompactPreview, persisted as text. The BlurHash placeholder "
 68250                + "is not a proxy: it is the Metadata.Blurhash column.");
 68251
 68252            entity.HasIndex(p => new { p.AssetId, p.ProxyType })
 68253                  .IsUnique()
 68254                  .HasDatabaseName(ProxyFileIndexNames.OnePerAssetAndType);
 68255            entity.HasIndex(p => p.ProxyPath)
 68256                  .HasOperators("text_pattern_ops")
 68257                  .HasDatabaseName(ProxyFileIndexNames.ProxyPath);
 68258            entity.Property(p => p.ProxyType).HasConversion<string>();
 68259            entity.HasQueryFilter(e => !e.Asset.IsSoftDeleted);
 68260        });
 261
 68262        modelBuilder.Entity<RefreshToken>(entity =>
 68263        {
 68264            entity.ToTable(t => t.HasComment(
 68265                    "Issued and revoked by the API; expired rows are swept by the Worker's "
 68266                    + "TokenCleanup work item. One of the few tables both services touch."
 68267                ));
 68268            entity.Property(r => r.TokenHash).HasComment(
 68269                "Hash, never the token itself — a database disclosure must not hand out usable "
 68270                + "sessions.");
 68271
 68272            entity.Property(r => r.ReplacedById).HasComment(
 68273                "The token this one was rotated into. Presenting this token shortly after RevokedAt, "
 68274                + "while that one is still active, is a lost refresh response, not theft: the "
 68275                + "successor is rotated in its place (ADR 0017 sets the window).");
 68276
 68277            entity.HasIndex(r => r.TokenHash).IsUnique();
 68278            entity.HasIndex(r => new { r.UserId, r.ExpiresAt });
 68279
 68280            entity.HasOne(r => r.ReplacedBy)
 68281                  .WithOne()
 68282                  .HasForeignKey<RefreshToken>(r => r.ReplacedById)
 68283                  .OnDelete(DeleteBehavior.SetNull);
 68284
 68285            // Stryker disable once Statement
 68286            entity.HasOne(r => r.User)
 68287                  .WithMany(u => u.RefreshTokens)
 68288                  .HasForeignKey(r => r.UserId)
 68289                  .OnDelete(DeleteBehavior.Cascade);
 68290        });
 291
 68292        modelBuilder.Entity<Invite>(entity =>
 68293        {
 68294            entity.ToTable(t => t.HasComment(
 68295                    "Admin-issued registration tokens. Registration requires one; the first user "
 68296                    + "(bootstrap admin) is exempt. Redemption is a read-then-write race, which is "
 68297                    + "why this is the only table carrying a concurrency token."
 68298                ));
 68299            entity.Property(i => i.TokenHash).HasComment(
 68300                "Hash, never the token itself. 44 chars — base64 of a 32-byte value.");
 68301
 68302            entity.HasIndex(i => i.TokenHash).IsUnique();
 68303            entity.Property(i => i.TokenHash).HasMaxLength(44);
 68304
 68305            // xmin is a Postgres system column incremented on every UPDATE.
 68306            // Npgsql recognises the "xmin" column name and excludes it from migrations.
 68307            entity.Property<uint>("xmin")
 68308                  .HasColumnName("xmin")
 68309                  .ValueGeneratedOnAddOrUpdate()
 68310                  .IsConcurrencyToken();
 68311
 68312            entity.HasOne(i => i.CreatedBy)
 68313                  .WithMany()
 68314                  .HasForeignKey(i => i.CreatedByUserId)
 68315                  .OnDelete(DeleteBehavior.SetNull);
 68316
 68317            entity.HasOne(i => i.UsedBy)
 68318                  .WithMany()
 68319                  .HasForeignKey(i => i.UsedByUserId)
 68320                  .OnDelete(DeleteBehavior.SetNull);
 68321        });
 322
 68323        modelBuilder.Entity<User>(entity =>
 68324        {
 68325            entity.ToTable(t => t.HasComment(
 68326                    "Owns storage configs and interactions. All identity writes happen in the API; "
 68327                    + "the Worker only reads."
 68328                ));
 68329            entity.Property(u => u.PasswordHash).HasComment(
 68330                "Argon2id. The parameters live with the hasher, not here, so rotating them does "
 68331                + "not require a migration.");
 68332            entity.Property(u => u.MustChangePassword).HasComment(
 68333                "Set by an admin reset. Every protected route then answers 403 except the handful "
 68334                + "needed to change it.");
 68335
 68336            entity.Property(u => u.Username)
 68337                  .HasConversion(v => IdentityNormalizer.Normalize(v), v => v)
 68338                  .HasComment(identityNormalizedComment);
 68339            entity.Property(u => u.Email)
 68340                  .HasConversion(v => IdentityNormalizer.Normalize(v), v => v)
 68341                  .HasComment(identityNormalizedComment);
 68342
 68343            entity.HasIndex(u => u.Username).IsUnique().HasDatabaseName(UserIndexNames.UsernameUnique);
 68344            entity.HasIndex(u => u.Email).IsUnique().HasDatabaseName(UserIndexNames.EmailUnique);
 68345
 68346            // 1:N with StorageConfig
 68347            // Stryker disable once Statement
 68348            entity.HasMany(u => u.StorageConfigs)
 68349                  .WithOne(s => s.User)
 68350                  .HasForeignKey(s => s.UserId);
 68351
 68352            // 1:N with Interactions
 68353            // Stryker disable once Statement
 68354            entity.HasMany(u => u.Interactions)
 68355                  .WithOne(i => i.User)
 68356                  .HasForeignKey(i => i.UserId);
 68357        });
 358
 68359        modelBuilder.Entity<UserStorageConfig>(entity =>
 68360        {
 68361            entity.ToTable(t => t.HasComment(
 68362                    "A NAS root assigned to one user. This is the boundary that scopes assets to a "
 68363                    + "user and lets several Workers each monitor a separate config."
 68364                ));
 68365            entity.Property(s => s.RootPath).HasComment(
 68366                "GLOBALLY unique, not per user: a path cannot be assigned to two configs across "
 68367                + "all users. Two users indexing the same directory would duplicate every asset "
 68368                + "and let one user's config removal cascade away the other's rows.");
 68369
 68370            // Stryker disable once Statement
 68371            entity.HasIndex(s => s.UserId);
 68372            entity.HasIndex(s => s.RootPath).IsUnique().HasDatabaseName(StorageConfigIndexNames.RootPathUnique);
 68373
 68374            // 1:N with MediaAsset
 68375            // Stryker disable once Statement
 68376            entity.HasMany(s => s.Assets)
 68377                  .WithOne(a => a.StorageConfig)
 68378                  .HasForeignKey(a => a.StorageConfigId);
 68379        });
 380
 68381        modelBuilder.Entity<WorkItem>(entity =>
 68382        {
 68383            entity.ToTable(t => t.HasComment(
 68384                    "Durable work for the Worker, scheduled by Workers or requested by an admin. "
 68385                    + "Only IWorkQueue inserts rows; the API's only other write is an admin's cancel, and "
 68386                    + "every other state change belongs to the Worker's executor. Delivery is at least "
 68387                    + "once, so handlers start from scratch and converge."
 68388                ));
 68389            entity.Property(w => w.Kind).HasConversion<string>().HasComment(
 68390                "WorkKind, persisted as text. Picks the payload type and the handler through the "
 68391                + "registry, never through a switch.");
 68392            entity.Property(w => w.Payload).HasColumnType("jsonb").HasComment(
 68393                "The kind's IWorkPayload, serialised with System.Text.Json and NodaTime settings.");
 68394            entity.Property(w => w.DedupKey).HasComment(
 68395                "Opt-in coalescing. While an item with this key is Queued, enqueueing the same key "
 68396                + "returns that item instead of adding a second; the partial unique index enforces it.");
 68397            entity.Property(w => w.StorageConfigId).HasComment(
 68398                "The storage config the work belongs to, or null for unscoped work. A per-user Worker "
 68399                + "claims only its user's configs and unscoped work; deleting the config deletes its items. "
 68400                + "At most one item per config is Running, across all Workers, so two attempts never touch "
 68401                + "one config's files at once: the claim passes over a busy config, and a partial unique "
 68402                + "index rejects a racing second claim.");
 68403            entity.Property(w => w.RequestedBy).HasComment(
 68404                "The admin who asked for the work; null when a Worker's scheduler enqueued it.");
 68405            entity.Property(w => w.Status).HasConversion<string>().HasComment(
 68406                "Queued, Running, Succeeded, Failed or Cancelled, persisted as text.");
 68407            entity.Property(w => w.Attempt).HasComment(
 68408                "Incremented by every claim. Every write a Worker makes while running an item is "
 68409                + "fenced by (Id, Attempt), so an attempt that lost its lease changes nothing.");
 68410            entity.Property(w => w.Stalls).HasComment(
 68411                "Lease expiries, counted by lease recovery. A graceful shutdown hands the item back "
 68412                + "without counting one; the item fails as stalled once the limit is reached.");
 68413            entity.Property(w => w.ClaimedBy).HasComment(
 68414                "The claiming Worker for display: its WORKER__USER or 'all', then its host name.");
 68415            entity.Property(w => w.LeaseUntil).HasComment(
 68416                "Extended by every heartbeat. A Running item past it belongs to a dead or paused "
 68417                + "Worker and goes back to the queue.");
 68418            entity.Property(w => w.UpdatedAt).HasComment(
 68419                "Moves on every insert, claim and transition, and on a heartbeat only when the progress "
 68420                + "snapshot changed, so a reader can ask what changed since a point in time.");
 68421            entity.Property(w => w.CancelRequestedAt).HasComment(
 68422                "When an admin asked to cancel the item. A Queued item is cancelled at once; a Running "
 68423                + "one keeps running until the Worker's next heartbeat reads this and cancels its handler. "
 68424                + "A requested item is never queued again: release and lease recovery end it Cancelled. "
 68425                + "A cancelled periodic item counts as that run, so the next one follows a full interval later.");
 68426            entity.Property(w => w.ProgressNote).HasComment(
 68427                "The latest progress snapshot (done, optional total, note), overwritten by each "
 68428                + "heartbeat; no history is kept.");
 68429            entity.Property(w => w.Result).HasColumnType("jsonb").HasComment(
 68430                "The handler's results summary, written when the item succeeds, or when it is "
 68431                + "cancelled after its handler returned one; a Cancelled item's results are partial.");
 68432
 68433            entity.HasIndex(w => w.RequestedAt)
 68434                  .HasFilter(@"""Status"" = 'Queued'")
 68435                  .HasDatabaseName("ix_workitems_claim");
 68436            entity.HasIndex(w => w.DedupKey)
 68437                  .IsUnique()
 68438                  .HasFilter(@"""Status"" = 'Queued' AND ""DedupKey"" IS NOT NULL")
 68439                  .HasDatabaseName(WorkItemIndexNames.QueuedDedupKeyUnique);
 68440            entity.HasIndex(w => w.StorageConfigId);
 68441            entity.HasIndex(w => w.StorageConfigId, WorkItemIndexNames.RunningStorageConfigUnique)
 68442                  .IsUnique()
 68443                  .HasFilter(@"""Status"" = 'Running' AND ""StorageConfigId"" IS NOT NULL");
 68444            entity.HasIndex(w => w.LeaseUntil)
 68445                  .HasFilter(@"""Status"" = 'Running'")
 68446                  .HasDatabaseName("ix_workitems_lease");
 68447            entity.HasIndex(w => w.UpdatedAt);
 68448
 68449            entity.HasOne<UserStorageConfig>()
 68450                  .WithMany()
 68451                  .HasForeignKey(w => w.StorageConfigId)
 68452                  .OnDelete(DeleteBehavior.Cascade);
 68453
 68454            entity.HasOne<User>()
 68455                  .WithMany()
 68456                  .HasForeignKey(w => w.RequestedBy)
 68457                  .OnDelete(DeleteBehavior.SetNull);
 68458        });
 459
 68460        modelBuilder.Entity<ProxyOrphan>(entity =>
 68461        {
 68462            entity.ToTable(t => t.HasComment(
 68463                    "A file under the proxy root that a ProxySweep found unreferenced by any ProxyFiles row, "
 68464                    + "soft-deleted assets' included, and last written more than an hour before the scan. "
 68465                    + "Written only by the Worker; the API reads it. Nothing is deleted until an admin asks, "
 68466                    + "and a ProxyDeletion re-checks each file before it removes it."
 68467                ));
 68468            entity.Property(o => o.SweepId).HasComment(
 68469                "The ProxySweep work item that found the file; retention of the item purges its report.");
 68470            entity.Property(o => o.ProxyPath).HasComment(
 68471                "Path relative to the proxy root, compared as is with ProxyFiles.ProxyPath.");
 68472            entity.Property(o => o.StorageConfigId).HasComment(
 68473                "The storage config named by the file's directory, read through IProxyDirectoryStrategy; "
 68474                + "null when the path names none. No foreign key: the config may be gone already, or go later.");
 68475            entity.Property(o => o.SizeBytes).HasComment(
 68476                "Size at the scan. A deletion skips the file when its size has changed since.");
 68477            entity.Property(o => o.LastWriteTime).HasComment(
 68478                "Last write time at the scan, truncated to microseconds. A deletion skips the file when it "
 68479                + "has changed since.");
 68480            entity.Property(o => o.DeletionOutcome).HasConversion<string>().HasComment(
 68481                "Deleted, SkippedReferenced, SkippedChanged, Missing or Failed, persisted as text; null until "
 68482                + "a deletion processed the file. A processed orphan is never processed again.");
 68483
 68484            entity.HasIndex(o => new { o.SweepId, o.ProxyPath })
 68485                  .IsUnique()
 68486                  .HasDatabaseName(ProxyOrphanIndexNames.OnePerSweepAndPath);
 68487
 68488            entity.HasOne<WorkItem>()
 68489                  .WithMany()
 68490                  .HasForeignKey(o => o.SweepId)
 68491                  .OnDelete(DeleteBehavior.Cascade);
 68492        });
 68493    }
 494}