| | | 1 | | using Anichron.Core.Domain; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; |
| | | 4 | | |
| | | 5 | | namespace Anichron.Core.Data; |
| | | 6 | | |
| | 1308 | 7 | | public 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 | | |
| | 154 | 14 | | public DbSet<User> Users => Set<User>(); |
| | 237 | 15 | | public DbSet<UserStorageConfig> StorageConfigs => Set<UserStorageConfig>(); |
| | 862 | 16 | | public DbSet<MediaAsset> MediaAssets => Set<MediaAsset>(); |
| | 15 | 17 | | public DbSet<Metadata> Metadata => Set<Metadata>(); |
| | 120 | 18 | | public DbSet<ProxyFile> ProxyFiles => Set<ProxyFile>(); |
| | 259 | 19 | | public DbSet<Burst> Bursts => Set<Burst>(); |
| | 856 | 20 | | public DbSet<BurstCheck> BurstChecks => Set<BurstCheck>(); |
| | 205 | 21 | | public DbSet<AssetInteraction> Interactions => Set<AssetInteraction>(); |
| | 13 | 22 | | public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>(); |
| | 11 | 23 | | public DbSet<Invite> Invites => Set<Invite>(); |
| | 104 | 24 | | public DbSet<WorkItem> WorkItems => Set<WorkItem>(); |
| | 31 | 25 | | public DbSet<ProxyOrphan> ProxyOrphans => Set<ProxyOrphan>(); |
| | | 26 | | |
| | | 27 | | // Stryker disable all |
| | | 28 | | public async Task ExecuteInTransactionAsync(Func<Task> action, CancellationToken ct = default) |
| | 0 | 29 | | { |
| | 0 | 30 | | await using var tx = await Database.BeginTransactionAsync(ct); |
| | 0 | 31 | | await action(); |
| | 0 | 32 | | await tx.CommitAsync(ct); |
| | 0 | 33 | | } |
| | | 34 | | |
| | | 35 | | protected override void OnModelCreating(ModelBuilder modelBuilder) |
| | 68 | 36 | | { |
| | | 37 | | // Stryker disable once Statement |
| | 68 | 38 | | base.OnModelCreating(modelBuilder); |
| | | 39 | | |
| | 68 | 40 | | modelBuilder.Entity<AssetInteraction>(entity => |
| | 68 | 41 | | { |
| | 68 | 42 | | entity.ToTable(t => t.HasComment( |
| | 68 | 43 | | "Per-user state for one asset. Never shared between users: two people looking at " |
| | 68 | 44 | | + "the same file each get their own row. Drives flashback weighting — hidden " |
| | 68 | 45 | | + "excludes, starred always includes and sorts first, liked raises DisplayWeight." |
| | 68 | 46 | | )); |
| | 68 | 47 | | entity.Property(i => i.HiddenAt).HasComment( |
| | 68 | 48 | | "When the user last hid the asset; NULL while it is shown. Orders the user's hidden memories, " |
| | 68 | 49 | | + "newest first."); |
| | 68 | 50 | | entity.HasIndex(i => new { i.UserId, i.AssetId }).IsUnique().HasDatabaseName(InteractionIndexNames.OnePerUse |
| | 68 | 51 | | entity.HasQueryFilter(i => !i.Asset.IsSoftDeleted); |
| | 68 | 52 | | }); |
| | | 53 | | |
| | 68 | 54 | | modelBuilder.Entity<Burst>(entity => |
| | 68 | 55 | | { |
| | 68 | 56 | | entity.ToTable(t => t.HasComment( |
| | 68 | 57 | | "Groups photos of one storage config taken moments apart, so a flashback shows one " |
| | 68 | 58 | | + "memory rather than nine near-identical frames. Written only by the Worker's " |
| | 68 | 59 | | + "BurstDetection work item, which also repairs bursts: one left with fewer than two " |
| | 68 | 60 | | + "active members is deleted, and so is one with no members at all." |
| | 68 | 61 | | )); |
| | 68 | 62 | | entity.Property(b => b.PrimaryAssetId).HasComment( |
| | 68 | 63 | | "The stored cover, the earliest member. SetNull on delete, so deleting the cover's row " |
| | 68 | 64 | | + "(a storage config removal cascading to its assets) cannot fail on the burst; the " |
| | 68 | 65 | | + "next BurstDetection run picks a new cover or deletes the burst."); |
| | 68 | 66 | | |
| | 68 | 67 | | entity.HasOne(b => b.PrimaryAsset) |
| | 68 | 68 | | .WithMany() |
| | 68 | 69 | | .HasForeignKey(b => b.PrimaryAssetId) |
| | 68 | 70 | | .OnDelete(DeleteBehavior.SetNull); |
| | 68 | 71 | | entity.HasQueryFilter(b => b.PrimaryAssetId == null || !b.PrimaryAsset!.IsSoftDeleted); |
| | 68 | 72 | | }); |
| | | 73 | | |
| | 68 | 74 | | modelBuilder.Entity<BurstCheck>(entity => |
| | 68 | 75 | | { |
| | 68 | 76 | | entity.ToTable(t => t.HasComment( |
| | 68 | 77 | | "One row per photo burst detection has checked; no row means unchecked. Owned by the " |
| | 68 | 78 | | + "BurstDetection work item, which reads the original once when it checks a photo. " |
| | 68 | 79 | | + "A file edited in place loses its row, so it is checked again." |
| | 68 | 80 | | )); |
| | 68 | 81 | | entity.Property(c => c.IsCandidate).HasComment( |
| | 68 | 82 | | "The photo has an EXIF capture time, a camera make and model, and a thumbnail; only " |
| | 68 | 83 | | + "candidates are grouped. False also when the original could not be read."); |
| | 68 | 84 | | entity.Property(c => c.CameraBurstId).HasComment( |
| | 68 | 85 | | "Apple's BurstUUID from the original's maker note: photos of one storage config " |
| | 68 | 86 | | + "sharing it form one burst. Null when the camera wrote none."); |
| | 68 | 87 | | entity.HasKey(c => c.AssetId); |
| | 68 | 88 | | |
| | 68 | 89 | | entity.HasOne(c => c.Asset) |
| | 68 | 90 | | .WithOne() |
| | 68 | 91 | | .HasForeignKey<BurstCheck>(c => c.AssetId) |
| | 68 | 92 | | .OnDelete(DeleteBehavior.Cascade); |
| | 68 | 93 | | entity.HasIndex(c => c.CameraBurstId); |
| | 68 | 94 | | entity.HasQueryFilter(c => !c.Asset.IsSoftDeleted); |
| | 68 | 95 | | }); |
| | | 96 | | |
| | 68 | 97 | | modelBuilder.Entity<MediaAsset>(entity => |
| | 68 | 98 | | { |
| | 68 | 99 | | entity.ToTable(t => t.HasComment( |
| | 68 | 100 | | "One row per media file, scoped to a storage config. Written ONLY by the Worker — " |
| | 68 | 101 | | + "the API never writes media data." |
| | 68 | 102 | | )); |
| | 68 | 103 | | entity.Property(m => m.ContentHash).HasComment( |
| | 68 | 104 | | "XXHash64 of the file contents. Dedup is deliberately CONFIG-SCOPED: the same " |
| | 68 | 105 | | + "bytes under two storage configs are two assets, which is what makes multi-user " |
| | 68 | 106 | | + "work. A global unique index on this column alone would break that and must " |
| | 68 | 107 | | + "never be added."); |
| | 68 | 108 | | entity.Property(m => m.FilePath).HasComment( |
| | 68 | 109 | | "Path relative to the storage config root. Not to be confused with " |
| | 68 | 110 | | + "ProxyFiles.ProxyPath, which is relative to the proxy root."); |
| | 68 | 111 | | entity.Property(m => m.DateCaptured).HasComment( |
| | 68 | 112 | | "The wall-clock time the file records it was captured. NULL when it records none: the asset " |
| | 68 | 113 | | + "is undated, never dated by the file's last-modified time, and is left out of On This Day " |
| | 68 | 114 | | + "and burst detection (ADR 0015)."); |
| | 68 | 115 | | entity.Ignore(m => m.Captured); |
| | 68 | 116 | | entity.Property(m => m.CaptureOffset) |
| | 68 | 117 | | .HasConversion(new ValueConverter<Offset, int>(offset => offset.Seconds, seconds => Offset.FromSeconds |
| | 68 | 118 | | .HasComment( |
| | 68 | 119 | | "Seconds east of UTC that the file records with DateCaptured; NULL when it records none. " |
| | 68 | 120 | | + "Kept as recorded, even when it disagrees with CaptureZone (ADR 0015)."); |
| | 68 | 121 | | entity.Property(m => m.CaptureSource).HasConversion<string>().HasComment( |
| | 68 | 122 | | "Which kind of source DateCaptured came from; NULL exactly when DateCaptured is."); |
| | 68 | 123 | | entity.Property(m => m.CaptureZone).HasComment( |
| | 68 | 124 | | "IANA time zone at the asset's position when it was ingested, looked up offline; NULL without " |
| | 68 | 125 | | + "a position. Never changes DateCaptured or CaptureOffset."); |
| | 68 | 126 | | entity.Property(m => m.Month).HasComment( |
| | 68 | 127 | | "Stored apart from DateCaptured so \"On This Day\" is an index lookup on " |
| | 68 | 128 | | + "(Month, Day) rather than an EXTRACT() scan over every row."); |
| | 68 | 129 | | entity.Property(m => m.Day).HasComment( |
| | 68 | 130 | | "See Month — the pair backs IX_MediaAsset_Flashback."); |
| | 68 | 131 | | entity.Property(m => m.PairedAssetId).HasComment( |
| | 68 | 132 | | "Live Photo pairing: the photo points at its video. The video is part of the photo, never a " |
| | 68 | 133 | | + "memory of its own, and has at most one photo (unique): pairing hands it over, reconciliation " |
| | 68 | 134 | | + "soft-deletes it with its photo and leaves a lone copy of it alone. Without its video the photo " |
| | 68 | 135 | | + "is shown as a still photo, so SetNull on delete."); |
| | 68 | 136 | | entity.Property(m => m.IsLivePhotoVideo).HasComment( |
| | 68 | 137 | | "Whether the row is a Live Photo's video: set when a photo is paired with it, never cleared, even " |
| | 68 | 138 | | + "when the photo lets go of it or is purged. Pairing soft-deletes a video its photo lets go of, and " |
| | 68 | 139 | | + "a flagged video crawled alone follows only its photo, so it is never a memory of its own (ADR 0019)." |
| | 68 | 140 | | entity.Property(m => m.IsSoftDeleted).HasComment( |
| | 68 | 141 | | "Set by reconciliation when a complete crawl did not find the file, or when its path " |
| | 68 | 142 | | + "now holds content stored at another path. Soft rather than hard so the user's " |
| | 68 | 143 | | + "interactions survive, and a crawl that finds the file again clears it (auto-restore)."); |
| | 68 | 144 | | |
| | 68 | 145 | | // Composite Index for "On This Day" (Optimized for Flashbacks) |
| | 68 | 146 | | entity.HasIndex(m => new { m.Month, m.Day }).HasDatabaseName("IX_MediaAsset_Flashback"); |
| | 68 | 147 | | |
| | 68 | 148 | | // One active asset per (config, hash) |
| | 68 | 149 | | entity.HasIndex(m => new { m.StorageConfigId, m.ContentHash }, MediaAssetIndexNames.ActiveContentHashUnique) |
| | 68 | 150 | | .IsUnique() |
| | 68 | 151 | | .HasFilter(@"""IsSoftDeleted"" = false"); |
| | 68 | 152 | | |
| | 68 | 153 | | entity.HasIndex(m => new { m.StorageConfigId, m.ContentHash }, MediaAssetIndexNames.SoftDeletedContentHash) |
| | 68 | 154 | | .HasFilter(@"""IsSoftDeleted"" = true"); |
| | 68 | 155 | | |
| | 68 | 156 | | // Unique Constraint: One file path per storage config |
| | 68 | 157 | | entity.HasIndex(m => new { m.StorageConfigId, m.FilePath }) |
| | 68 | 158 | | .IsUnique() |
| | 68 | 159 | | .HasDatabaseName(MediaAssetIndexNames.FilePathUnique); |
| | 68 | 160 | | |
| | 68 | 161 | | entity.HasIndex(m => new { m.StorageConfigId, m.DateCaptured }); |
| | 68 | 162 | | |
| | 68 | 163 | | entity.HasIndex(m => m.PairedAssetId) |
| | 68 | 164 | | .IsUnique() |
| | 68 | 165 | | .HasDatabaseName(MediaAssetIndexNames.PairedAssetIdUnique); |
| | 68 | 166 | | |
| | 68 | 167 | | // Self-Reference (Paired Asset) |
| | 68 | 168 | | entity.HasOne(m => m.PairedAsset) |
| | 68 | 169 | | .WithMany() |
| | 68 | 170 | | .HasForeignKey(m => m.PairedAssetId) |
| | 68 | 171 | | .OnDelete(DeleteBehavior.SetNull); |
| | 68 | 172 | | |
| | 68 | 173 | | // N:1 with Burst |
| | 68 | 174 | | entity.HasOne(m => m.Burst) |
| | 68 | 175 | | .WithMany(b => b.Assets) |
| | 68 | 176 | | .HasForeignKey(m => m.BurstId) |
| | 68 | 177 | | .OnDelete(DeleteBehavior.SetNull); // Keeping the photo if the burst is dissolved |
| | 68 | 178 | | |
| | 68 | 179 | | // 1:N with ProxyFiles |
| | 68 | 180 | | // Stryker disable once Statement |
| | 68 | 181 | | entity.HasMany(m => m.ProxyFiles) |
| | 68 | 182 | | .WithOne(p => p.Asset) |
| | 68 | 183 | | .HasForeignKey(p => p.AssetId) |
| | 68 | 184 | | .OnDelete(DeleteBehavior.Cascade); |
| | 68 | 185 | | |
| | 68 | 186 | | // 1:N with Interactions |
| | 68 | 187 | | // Stryker disable once Statement |
| | 68 | 188 | | entity.HasMany(m => m.Interactions) |
| | 68 | 189 | | .WithOne(i => i.Asset) |
| | 68 | 190 | | .HasForeignKey(i => i.AssetId); |
| | 68 | 191 | | |
| | 68 | 192 | | // Partial index covering only active (non-deleted) assets |
| | 68 | 193 | | entity.HasIndex(m => m.IsSoftDeleted) |
| | 68 | 194 | | .HasFilter(@"""IsSoftDeleted"" = false") |
| | 68 | 195 | | .HasDatabaseName("IX_MediaAssets_Active"); |
| | 68 | 196 | | |
| | 68 | 197 | | // Global Query Filter: Hide soft-deleted files by default |
| | 68 | 198 | | entity.HasQueryFilter(m => !m.IsSoftDeleted); |
| | 68 | 199 | | |
| | 68 | 200 | | // Enum Conversion |
| | 68 | 201 | | entity.Property(m => m.MediaType).HasConversion<string>(); |
| | 68 | 202 | | }); |
| | | 203 | | |
| | 68 | 204 | | modelBuilder.Entity<Metadata>(entity => |
| | 68 | 205 | | { |
| | 68 | 206 | | entity.ToTable(t => t.HasComment( |
| | 68 | 207 | | "What a file records in its EXIF, XMP, IPTC, QuickTime or AVI metadata, 1:1 with MediaAsset and " |
| | 68 | 208 | | + "keyed by it — there is no separate Id. Populated by MetadataExtractionMiddleware; every field " |
| | 68 | 209 | | + "is best-effort, because a file may record none of it." |
| | 68 | 210 | | )); |
| | 68 | 211 | | entity.OwnsOne(m => m.Description, description => description.Property(d => d.Orientation) |
| | 68 | 212 | | .HasDefaultValue(ExifOrientation.Upright) |
| | 68 | 213 | | .HasComment( |
| | 68 | 214 | | "EXIF orientation value, 1-8 (1 = upright, also used when absent or invalid): " |
| | 68 | 215 | | + "from the container's irot for a HEIC, the video track's rotation for a video, " |
| | 68 | 216 | | + "and the EXIF tag otherwise. Kept as an EXIF value because 5 and 7 combine a " |
| | 68 | 217 | | + "rotation with a mirror and cannot be expressed as degrees; a reader converts, " |
| | 68 | 218 | | + "and for 5-8 swaps Width/Height. Proxies are already upright and a video's " |
| | 68 | 219 | | + "player applies its own rotation, so rotate neither by it.")); |
| | 68 | 220 | | entity.Property(m => m.Blurhash).HasComment( |
| | 68 | 221 | | "BlurHash placeholder string (4x3 components), computed by the Worker from the " |
| | 68 | 222 | | + "upright image. Kept here rather than as a proxy file so a response needs no disk " |
| | 68 | 223 | | + "read for it. A video's is computed from its poster. Null for assets ingested " |
| | 68 | 224 | | + "before the column existed, which are not backfilled."); |
| | 68 | 225 | | entity.HasKey(m => m.AssetId); |
| | 68 | 226 | | |
| | 68 | 227 | | // 1:1 with MediaAsset |
| | 68 | 228 | | // Stryker disable once Statement |
| | 68 | 229 | | entity.HasOne(m => m.Asset) |
| | 68 | 230 | | .WithOne(a => a.Metadata) |
| | 68 | 231 | | .HasForeignKey<Metadata>(m => m.AssetId) |
| | 68 | 232 | | .OnDelete(DeleteBehavior.Cascade); |
| | 68 | 233 | | entity.HasQueryFilter(e => !e.Asset.IsSoftDeleted); |
| | 68 | 234 | | }); |
| | | 235 | | |
| | 68 | 236 | | modelBuilder.Entity<ProxyFile>(entity => |
| | 68 | 237 | | { |
| | 68 | 238 | | entity.ToTable(t => t.HasComment( |
| | 68 | 239 | | "One row per generated artefact on the local SSD. An asset has several, but at " |
| | 68 | 240 | | + "most one per ProxyType, so of two attempts racing to add the same proxy only one " |
| | 68 | 241 | | + "row lands. Written only by ProxyStagingWriter, at the moment the file reaches " |
| | 68 | 242 | | + "its final name." |
| | 68 | 243 | | )); |
| | 68 | 244 | | entity.Property(p => p.ProxyPath).HasComment( |
| | 68 | 245 | | "Path relative to the proxy root, sharded by CONTENT rather than by ingestion " |
| | 68 | 246 | | + "attempt so a retry overwrites its own debris instead of stranding it. " |
| | 68 | 247 | | + "IProxyDirectoryStrategy is the single place that rule lives."); |
| | 68 | 248 | | entity.Property(p => p.ProxyType).HasComment( |
| | 68 | 249 | | "Thumbnail, WebVideo, FullPreview or CompactPreview, persisted as text. The BlurHash placeholder " |
| | 68 | 250 | | + "is not a proxy: it is the Metadata.Blurhash column."); |
| | 68 | 251 | | |
| | 68 | 252 | | entity.HasIndex(p => new { p.AssetId, p.ProxyType }) |
| | 68 | 253 | | .IsUnique() |
| | 68 | 254 | | .HasDatabaseName(ProxyFileIndexNames.OnePerAssetAndType); |
| | 68 | 255 | | entity.HasIndex(p => p.ProxyPath) |
| | 68 | 256 | | .HasOperators("text_pattern_ops") |
| | 68 | 257 | | .HasDatabaseName(ProxyFileIndexNames.ProxyPath); |
| | 68 | 258 | | entity.Property(p => p.ProxyType).HasConversion<string>(); |
| | 68 | 259 | | entity.HasQueryFilter(e => !e.Asset.IsSoftDeleted); |
| | 68 | 260 | | }); |
| | | 261 | | |
| | 68 | 262 | | modelBuilder.Entity<RefreshToken>(entity => |
| | 68 | 263 | | { |
| | 68 | 264 | | entity.ToTable(t => t.HasComment( |
| | 68 | 265 | | "Issued and revoked by the API; expired rows are swept by the Worker's " |
| | 68 | 266 | | + "TokenCleanup work item. One of the few tables both services touch." |
| | 68 | 267 | | )); |
| | 68 | 268 | | entity.Property(r => r.TokenHash).HasComment( |
| | 68 | 269 | | "Hash, never the token itself — a database disclosure must not hand out usable " |
| | 68 | 270 | | + "sessions."); |
| | 68 | 271 | | |
| | 68 | 272 | | entity.Property(r => r.ReplacedById).HasComment( |
| | 68 | 273 | | "The token this one was rotated into. Presenting this token shortly after RevokedAt, " |
| | 68 | 274 | | + "while that one is still active, is a lost refresh response, not theft: the " |
| | 68 | 275 | | + "successor is rotated in its place (ADR 0017 sets the window)."); |
| | 68 | 276 | | |
| | 68 | 277 | | entity.HasIndex(r => r.TokenHash).IsUnique(); |
| | 68 | 278 | | entity.HasIndex(r => new { r.UserId, r.ExpiresAt }); |
| | 68 | 279 | | |
| | 68 | 280 | | entity.HasOne(r => r.ReplacedBy) |
| | 68 | 281 | | .WithOne() |
| | 68 | 282 | | .HasForeignKey<RefreshToken>(r => r.ReplacedById) |
| | 68 | 283 | | .OnDelete(DeleteBehavior.SetNull); |
| | 68 | 284 | | |
| | 68 | 285 | | // Stryker disable once Statement |
| | 68 | 286 | | entity.HasOne(r => r.User) |
| | 68 | 287 | | .WithMany(u => u.RefreshTokens) |
| | 68 | 288 | | .HasForeignKey(r => r.UserId) |
| | 68 | 289 | | .OnDelete(DeleteBehavior.Cascade); |
| | 68 | 290 | | }); |
| | | 291 | | |
| | 68 | 292 | | modelBuilder.Entity<Invite>(entity => |
| | 68 | 293 | | { |
| | 68 | 294 | | entity.ToTable(t => t.HasComment( |
| | 68 | 295 | | "Admin-issued registration tokens. Registration requires one; the first user " |
| | 68 | 296 | | + "(bootstrap admin) is exempt. Redemption is a read-then-write race, which is " |
| | 68 | 297 | | + "why this is the only table carrying a concurrency token." |
| | 68 | 298 | | )); |
| | 68 | 299 | | entity.Property(i => i.TokenHash).HasComment( |
| | 68 | 300 | | "Hash, never the token itself. 44 chars — base64 of a 32-byte value."); |
| | 68 | 301 | | |
| | 68 | 302 | | entity.HasIndex(i => i.TokenHash).IsUnique(); |
| | 68 | 303 | | entity.Property(i => i.TokenHash).HasMaxLength(44); |
| | 68 | 304 | | |
| | 68 | 305 | | // xmin is a Postgres system column incremented on every UPDATE. |
| | 68 | 306 | | // Npgsql recognises the "xmin" column name and excludes it from migrations. |
| | 68 | 307 | | entity.Property<uint>("xmin") |
| | 68 | 308 | | .HasColumnName("xmin") |
| | 68 | 309 | | .ValueGeneratedOnAddOrUpdate() |
| | 68 | 310 | | .IsConcurrencyToken(); |
| | 68 | 311 | | |
| | 68 | 312 | | entity.HasOne(i => i.CreatedBy) |
| | 68 | 313 | | .WithMany() |
| | 68 | 314 | | .HasForeignKey(i => i.CreatedByUserId) |
| | 68 | 315 | | .OnDelete(DeleteBehavior.SetNull); |
| | 68 | 316 | | |
| | 68 | 317 | | entity.HasOne(i => i.UsedBy) |
| | 68 | 318 | | .WithMany() |
| | 68 | 319 | | .HasForeignKey(i => i.UsedByUserId) |
| | 68 | 320 | | .OnDelete(DeleteBehavior.SetNull); |
| | 68 | 321 | | }); |
| | | 322 | | |
| | 68 | 323 | | modelBuilder.Entity<User>(entity => |
| | 68 | 324 | | { |
| | 68 | 325 | | entity.ToTable(t => t.HasComment( |
| | 68 | 326 | | "Owns storage configs and interactions. All identity writes happen in the API; " |
| | 68 | 327 | | + "the Worker only reads." |
| | 68 | 328 | | )); |
| | 68 | 329 | | entity.Property(u => u.PasswordHash).HasComment( |
| | 68 | 330 | | "Argon2id. The parameters live with the hasher, not here, so rotating them does " |
| | 68 | 331 | | + "not require a migration."); |
| | 68 | 332 | | entity.Property(u => u.MustChangePassword).HasComment( |
| | 68 | 333 | | "Set by an admin reset. Every protected route then answers 403 except the handful " |
| | 68 | 334 | | + "needed to change it."); |
| | 68 | 335 | | |
| | 68 | 336 | | entity.Property(u => u.Username) |
| | 68 | 337 | | .HasConversion(v => IdentityNormalizer.Normalize(v), v => v) |
| | 68 | 338 | | .HasComment(identityNormalizedComment); |
| | 68 | 339 | | entity.Property(u => u.Email) |
| | 68 | 340 | | .HasConversion(v => IdentityNormalizer.Normalize(v), v => v) |
| | 68 | 341 | | .HasComment(identityNormalizedComment); |
| | 68 | 342 | | |
| | 68 | 343 | | entity.HasIndex(u => u.Username).IsUnique().HasDatabaseName(UserIndexNames.UsernameUnique); |
| | 68 | 344 | | entity.HasIndex(u => u.Email).IsUnique().HasDatabaseName(UserIndexNames.EmailUnique); |
| | 68 | 345 | | |
| | 68 | 346 | | // 1:N with StorageConfig |
| | 68 | 347 | | // Stryker disable once Statement |
| | 68 | 348 | | entity.HasMany(u => u.StorageConfigs) |
| | 68 | 349 | | .WithOne(s => s.User) |
| | 68 | 350 | | .HasForeignKey(s => s.UserId); |
| | 68 | 351 | | |
| | 68 | 352 | | // 1:N with Interactions |
| | 68 | 353 | | // Stryker disable once Statement |
| | 68 | 354 | | entity.HasMany(u => u.Interactions) |
| | 68 | 355 | | .WithOne(i => i.User) |
| | 68 | 356 | | .HasForeignKey(i => i.UserId); |
| | 68 | 357 | | }); |
| | | 358 | | |
| | 68 | 359 | | modelBuilder.Entity<UserStorageConfig>(entity => |
| | 68 | 360 | | { |
| | 68 | 361 | | entity.ToTable(t => t.HasComment( |
| | 68 | 362 | | "A NAS root assigned to one user. This is the boundary that scopes assets to a " |
| | 68 | 363 | | + "user and lets several Workers each monitor a separate config." |
| | 68 | 364 | | )); |
| | 68 | 365 | | entity.Property(s => s.RootPath).HasComment( |
| | 68 | 366 | | "GLOBALLY unique, not per user: a path cannot be assigned to two configs across " |
| | 68 | 367 | | + "all users. Two users indexing the same directory would duplicate every asset " |
| | 68 | 368 | | + "and let one user's config removal cascade away the other's rows."); |
| | 68 | 369 | | |
| | 68 | 370 | | // Stryker disable once Statement |
| | 68 | 371 | | entity.HasIndex(s => s.UserId); |
| | 68 | 372 | | entity.HasIndex(s => s.RootPath).IsUnique().HasDatabaseName(StorageConfigIndexNames.RootPathUnique); |
| | 68 | 373 | | |
| | 68 | 374 | | // 1:N with MediaAsset |
| | 68 | 375 | | // Stryker disable once Statement |
| | 68 | 376 | | entity.HasMany(s => s.Assets) |
| | 68 | 377 | | .WithOne(a => a.StorageConfig) |
| | 68 | 378 | | .HasForeignKey(a => a.StorageConfigId); |
| | 68 | 379 | | }); |
| | | 380 | | |
| | 68 | 381 | | modelBuilder.Entity<WorkItem>(entity => |
| | 68 | 382 | | { |
| | 68 | 383 | | entity.ToTable(t => t.HasComment( |
| | 68 | 384 | | "Durable work for the Worker, scheduled by Workers or requested by an admin. " |
| | 68 | 385 | | + "Only IWorkQueue inserts rows; the API's only other write is an admin's cancel, and " |
| | 68 | 386 | | + "every other state change belongs to the Worker's executor. Delivery is at least " |
| | 68 | 387 | | + "once, so handlers start from scratch and converge." |
| | 68 | 388 | | )); |
| | 68 | 389 | | entity.Property(w => w.Kind).HasConversion<string>().HasComment( |
| | 68 | 390 | | "WorkKind, persisted as text. Picks the payload type and the handler through the " |
| | 68 | 391 | | + "registry, never through a switch."); |
| | 68 | 392 | | entity.Property(w => w.Payload).HasColumnType("jsonb").HasComment( |
| | 68 | 393 | | "The kind's IWorkPayload, serialised with System.Text.Json and NodaTime settings."); |
| | 68 | 394 | | entity.Property(w => w.DedupKey).HasComment( |
| | 68 | 395 | | "Opt-in coalescing. While an item with this key is Queued, enqueueing the same key " |
| | 68 | 396 | | + "returns that item instead of adding a second; the partial unique index enforces it."); |
| | 68 | 397 | | entity.Property(w => w.StorageConfigId).HasComment( |
| | 68 | 398 | | "The storage config the work belongs to, or null for unscoped work. A per-user Worker " |
| | 68 | 399 | | + "claims only its user's configs and unscoped work; deleting the config deletes its items. " |
| | 68 | 400 | | + "At most one item per config is Running, across all Workers, so two attempts never touch " |
| | 68 | 401 | | + "one config's files at once: the claim passes over a busy config, and a partial unique " |
| | 68 | 402 | | + "index rejects a racing second claim."); |
| | 68 | 403 | | entity.Property(w => w.RequestedBy).HasComment( |
| | 68 | 404 | | "The admin who asked for the work; null when a Worker's scheduler enqueued it."); |
| | 68 | 405 | | entity.Property(w => w.Status).HasConversion<string>().HasComment( |
| | 68 | 406 | | "Queued, Running, Succeeded, Failed or Cancelled, persisted as text."); |
| | 68 | 407 | | entity.Property(w => w.Attempt).HasComment( |
| | 68 | 408 | | "Incremented by every claim. Every write a Worker makes while running an item is " |
| | 68 | 409 | | + "fenced by (Id, Attempt), so an attempt that lost its lease changes nothing."); |
| | 68 | 410 | | entity.Property(w => w.Stalls).HasComment( |
| | 68 | 411 | | "Lease expiries, counted by lease recovery. A graceful shutdown hands the item back " |
| | 68 | 412 | | + "without counting one; the item fails as stalled once the limit is reached."); |
| | 68 | 413 | | entity.Property(w => w.ClaimedBy).HasComment( |
| | 68 | 414 | | "The claiming Worker for display: its WORKER__USER or 'all', then its host name."); |
| | 68 | 415 | | entity.Property(w => w.LeaseUntil).HasComment( |
| | 68 | 416 | | "Extended by every heartbeat. A Running item past it belongs to a dead or paused " |
| | 68 | 417 | | + "Worker and goes back to the queue."); |
| | 68 | 418 | | entity.Property(w => w.UpdatedAt).HasComment( |
| | 68 | 419 | | "Moves on every insert, claim and transition, and on a heartbeat only when the progress " |
| | 68 | 420 | | + "snapshot changed, so a reader can ask what changed since a point in time."); |
| | 68 | 421 | | entity.Property(w => w.CancelRequestedAt).HasComment( |
| | 68 | 422 | | "When an admin asked to cancel the item. A Queued item is cancelled at once; a Running " |
| | 68 | 423 | | + "one keeps running until the Worker's next heartbeat reads this and cancels its handler. " |
| | 68 | 424 | | + "A requested item is never queued again: release and lease recovery end it Cancelled. " |
| | 68 | 425 | | + "A cancelled periodic item counts as that run, so the next one follows a full interval later."); |
| | 68 | 426 | | entity.Property(w => w.ProgressNote).HasComment( |
| | 68 | 427 | | "The latest progress snapshot (done, optional total, note), overwritten by each " |
| | 68 | 428 | | + "heartbeat; no history is kept."); |
| | 68 | 429 | | entity.Property(w => w.Result).HasColumnType("jsonb").HasComment( |
| | 68 | 430 | | "The handler's results summary, written when the item succeeds, or when it is " |
| | 68 | 431 | | + "cancelled after its handler returned one; a Cancelled item's results are partial."); |
| | 68 | 432 | | |
| | 68 | 433 | | entity.HasIndex(w => w.RequestedAt) |
| | 68 | 434 | | .HasFilter(@"""Status"" = 'Queued'") |
| | 68 | 435 | | .HasDatabaseName("ix_workitems_claim"); |
| | 68 | 436 | | entity.HasIndex(w => w.DedupKey) |
| | 68 | 437 | | .IsUnique() |
| | 68 | 438 | | .HasFilter(@"""Status"" = 'Queued' AND ""DedupKey"" IS NOT NULL") |
| | 68 | 439 | | .HasDatabaseName(WorkItemIndexNames.QueuedDedupKeyUnique); |
| | 68 | 440 | | entity.HasIndex(w => w.StorageConfigId); |
| | 68 | 441 | | entity.HasIndex(w => w.StorageConfigId, WorkItemIndexNames.RunningStorageConfigUnique) |
| | 68 | 442 | | .IsUnique() |
| | 68 | 443 | | .HasFilter(@"""Status"" = 'Running' AND ""StorageConfigId"" IS NOT NULL"); |
| | 68 | 444 | | entity.HasIndex(w => w.LeaseUntil) |
| | 68 | 445 | | .HasFilter(@"""Status"" = 'Running'") |
| | 68 | 446 | | .HasDatabaseName("ix_workitems_lease"); |
| | 68 | 447 | | entity.HasIndex(w => w.UpdatedAt); |
| | 68 | 448 | | |
| | 68 | 449 | | entity.HasOne<UserStorageConfig>() |
| | 68 | 450 | | .WithMany() |
| | 68 | 451 | | .HasForeignKey(w => w.StorageConfigId) |
| | 68 | 452 | | .OnDelete(DeleteBehavior.Cascade); |
| | 68 | 453 | | |
| | 68 | 454 | | entity.HasOne<User>() |
| | 68 | 455 | | .WithMany() |
| | 68 | 456 | | .HasForeignKey(w => w.RequestedBy) |
| | 68 | 457 | | .OnDelete(DeleteBehavior.SetNull); |
| | 68 | 458 | | }); |
| | | 459 | | |
| | 68 | 460 | | modelBuilder.Entity<ProxyOrphan>(entity => |
| | 68 | 461 | | { |
| | 68 | 462 | | entity.ToTable(t => t.HasComment( |
| | 68 | 463 | | "A file under the proxy root that a ProxySweep found unreferenced by any ProxyFiles row, " |
| | 68 | 464 | | + "soft-deleted assets' included, and last written more than an hour before the scan. " |
| | 68 | 465 | | + "Written only by the Worker; the API reads it. Nothing is deleted until an admin asks, " |
| | 68 | 466 | | + "and a ProxyDeletion re-checks each file before it removes it." |
| | 68 | 467 | | )); |
| | 68 | 468 | | entity.Property(o => o.SweepId).HasComment( |
| | 68 | 469 | | "The ProxySweep work item that found the file; retention of the item purges its report."); |
| | 68 | 470 | | entity.Property(o => o.ProxyPath).HasComment( |
| | 68 | 471 | | "Path relative to the proxy root, compared as is with ProxyFiles.ProxyPath."); |
| | 68 | 472 | | entity.Property(o => o.StorageConfigId).HasComment( |
| | 68 | 473 | | "The storage config named by the file's directory, read through IProxyDirectoryStrategy; " |
| | 68 | 474 | | + "null when the path names none. No foreign key: the config may be gone already, or go later."); |
| | 68 | 475 | | entity.Property(o => o.SizeBytes).HasComment( |
| | 68 | 476 | | "Size at the scan. A deletion skips the file when its size has changed since."); |
| | 68 | 477 | | entity.Property(o => o.LastWriteTime).HasComment( |
| | 68 | 478 | | "Last write time at the scan, truncated to microseconds. A deletion skips the file when it " |
| | 68 | 479 | | + "has changed since."); |
| | 68 | 480 | | entity.Property(o => o.DeletionOutcome).HasConversion<string>().HasComment( |
| | 68 | 481 | | "Deleted, SkippedReferenced, SkippedChanged, Missing or Failed, persisted as text; null until " |
| | 68 | 482 | | + "a deletion processed the file. A processed orphan is never processed again."); |
| | 68 | 483 | | |
| | 68 | 484 | | entity.HasIndex(o => new { o.SweepId, o.ProxyPath }) |
| | 68 | 485 | | .IsUnique() |
| | 68 | 486 | | .HasDatabaseName(ProxyOrphanIndexNames.OnePerSweepAndPath); |
| | 68 | 487 | | |
| | 68 | 488 | | entity.HasOne<WorkItem>() |
| | 68 | 489 | | .WithMany() |
| | 68 | 490 | | .HasForeignKey(o => o.SweepId) |
| | 68 | 491 | | .OnDelete(DeleteBehavior.Cascade); |
| | 68 | 492 | | }); |
| | 68 | 493 | | } |
| | | 494 | | } |