| | | 1 | | using Anichron.Core.Domain; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | |
| | | 4 | | namespace Anichron.Core.Data; |
| | | 5 | | |
| | 47 | 6 | | public class AnichronDbContext(DbContextOptions<AnichronDbContext> options) : DbContext(options), IUnitOfWork |
| | | 7 | | { |
| | 47 | 8 | | public DbSet<User> Users => Set<User>(); |
| | 25 | 9 | | public DbSet<UserStorageConfig> StorageConfigs => Set<UserStorageConfig>(); |
| | 0 | 10 | | public DbSet<MediaAsset> MediaAssets => Set<MediaAsset>(); |
| | 0 | 11 | | public DbSet<Metadata> Metadata => Set<Metadata>(); |
| | 0 | 12 | | public DbSet<ProxyFile> ProxyFiles => Set<ProxyFile>(); |
| | 0 | 13 | | public DbSet<Burst> Bursts => Set<Burst>(); |
| | 0 | 14 | | public DbSet<AssetInteraction> Interactions => Set<AssetInteraction>(); |
| | 8 | 15 | | public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>(); |
| | 9 | 16 | | public DbSet<Invite> Invites => Set<Invite>(); |
| | | 17 | | |
| | | 18 | | public async Task<T> ExecuteInTransactionAsync<T>(Func<Task<T>> action, CancellationToken ct = default) |
| | 0 | 19 | | { |
| | 0 | 20 | | await using var tx = await Database.BeginTransactionAsync(ct); |
| | 0 | 21 | | var result = await action(); |
| | 0 | 22 | | await tx.CommitAsync(ct); |
| | 0 | 23 | | return result; |
| | 0 | 24 | | } |
| | | 25 | | |
| | | 26 | | public async Task ExecuteInTransactionAsync(Func<Task> action, CancellationToken ct = default) |
| | 0 | 27 | | { |
| | 0 | 28 | | await using var tx = await Database.BeginTransactionAsync(ct); |
| | 0 | 29 | | await action(); |
| | 0 | 30 | | await tx.CommitAsync(ct); |
| | 0 | 31 | | } |
| | | 32 | | |
| | | 33 | | protected override void OnModelCreating(ModelBuilder modelBuilder) |
| | 1 | 34 | | { |
| | 1 | 35 | | base.OnModelCreating(modelBuilder); |
| | | 36 | | |
| | 1 | 37 | | modelBuilder.Entity<AssetInteraction>(entity => |
| | 1 | 38 | | { |
| | 1 | 39 | | entity.ToTable(t => t.HasComment( |
| | 1 | 40 | | "Per-user state for one asset. Never shared between users: two people looking at " |
| | 1 | 41 | | + "the same file each get their own row. Drives flashback weighting — hidden " |
| | 1 | 42 | | + "excludes, starred always includes and sorts first, liked raises DisplayWeight." |
| | 1 | 43 | | )); |
| | 1 | 44 | | entity.HasIndex(i => new { i.UserId, i.AssetId }).IsUnique(); |
| | 1 | 45 | | entity.HasQueryFilter(i => !i.Asset.IsSoftDeleted); |
| | 1 | 46 | | }); |
| | | 47 | | |
| | 1 | 48 | | modelBuilder.Entity<Burst>(entity => |
| | 1 | 49 | | { |
| | 1 | 50 | | entity.ToTable(t => t.HasComment( |
| | 1 | 51 | | "Groups a rapid-fire sequence so a flashback shows one memory rather than nine " |
| | 1 | 52 | | + "near-identical frames. The table and schema exist; burst DETECTION is not yet " |
| | 1 | 53 | | + "implemented in the Worker, so in a running system this table is empty." |
| | 1 | 54 | | )); |
| | 1 | 55 | | entity.Property(b => b.PrimaryAssetId).HasComment( |
| | 1 | 56 | | "The frame chosen to represent the burst. Restrict on delete: losing the cover " |
| | 1 | 57 | | + "would leave a group that cannot be rendered."); |
| | 1 | 58 | | |
| | 1 | 59 | | // Primary Asset reference (1:1 style lookup) |
| | 1 | 60 | | entity.HasOne(b => b.PrimaryAsset) |
| | 1 | 61 | | .WithMany() |
| | 1 | 62 | | .HasForeignKey(b => b.PrimaryAssetId) |
| | 1 | 63 | | .OnDelete(DeleteBehavior.Restrict); |
| | 1 | 64 | | entity.HasQueryFilter(b => !b.PrimaryAsset.IsSoftDeleted); |
| | 1 | 65 | | }); |
| | | 66 | | |
| | 1 | 67 | | modelBuilder.Entity<MediaAsset>(entity => |
| | 1 | 68 | | { |
| | 1 | 69 | | entity.ToTable(t => t.HasComment( |
| | 1 | 70 | | "One row per media file, scoped to a storage config. Written ONLY by the Worker — " |
| | 1 | 71 | | + "the API never writes media data." |
| | 1 | 72 | | )); |
| | 1 | 73 | | entity.Property(m => m.ContentHash).HasComment( |
| | 1 | 74 | | "XXHash64 of the file contents. Dedup is deliberately CONFIG-SCOPED: the same " |
| | 1 | 75 | | + "bytes under two storage configs are two assets, which is what makes multi-user " |
| | 1 | 76 | | + "work. A global unique index on this column alone would break that and must " |
| | 1 | 77 | | + "never be added."); |
| | 1 | 78 | | entity.Property(m => m.FilePath).HasComment( |
| | 1 | 79 | | "Path relative to the storage config root. Not to be confused with " |
| | 1 | 80 | | + "ProxyFiles.ProxyPath, which is relative to the proxy root."); |
| | 1 | 81 | | entity.Property(m => m.Month).HasComment( |
| | 1 | 82 | | "Stored apart from DateCaptured so \"On This Day\" is an index lookup on " |
| | 1 | 83 | | + "(Month, Day) rather than an EXTRACT() scan over every row."); |
| | 1 | 84 | | entity.Property(m => m.Day).HasComment( |
| | 1 | 85 | | "See Month — the pair backs IX_MediaAsset_Flashback."); |
| | 1 | 86 | | entity.Property(m => m.PairedAssetId).HasComment( |
| | 1 | 87 | | "Live Photo pairing: the HEIC parent points at its MOV child. SetNull on delete " |
| | 1 | 88 | | + "so losing one half leaves the other a usable standalone asset."); |
| | 1 | 89 | | entity.Property(m => m.IsSoftDeleted).HasComment( |
| | 1 | 90 | | "Set by reconciliation when a file is gone from the NAS. Soft rather than hard so " |
| | 1 | 91 | | + "the user's interactions survive a temporarily unmounted share."); |
| | 1 | 92 | | |
| | 1 | 93 | | // Composite Index for "On This Day" (Optimized for Flashbacks) |
| | 1 | 94 | | entity.HasIndex(m => new { m.Month, m.Day }).HasDatabaseName("IX_MediaAsset_Flashback"); |
| | 1 | 95 | | |
| | 1 | 96 | | // Index for Move Tracking (scoped to storage config for efficient idempotency lookups). |
| | 1 | 97 | | // ⚠️ Deliberately NOT unique today, and that is a known defect (#159): nothing enforces |
| | 1 | 98 | | // the "one active asset per (config, hash)" invariant IdempotencyCheckMiddleware |
| | 1 | 99 | | // assumes, so concurrent consumers can create silent duplicates. The fix is a |
| | 1 | 100 | | // config-scoped PARTIAL unique index filtered to active rows — not a plain unique |
| | 1 | 101 | | // index, which would collide with soft-deleted history. |
| | 1 | 102 | | entity.HasIndex(m => new { m.StorageConfigId, m.ContentHash }); |
| | 1 | 103 | | |
| | 1 | 104 | | // Unique Constraint: One file path per storage config. Unlike the hash index above |
| | 1 | 105 | | // this one IS enforced, so re-ingesting the same path cannot produce a second row |
| | 1 | 106 | | // even while #159 is open. |
| | 1 | 107 | | entity.HasIndex(m => new { m.StorageConfigId, m.FilePath }).IsUnique(); |
| | 1 | 108 | | |
| | 1 | 109 | | // Self-Reference (Paired Asset) |
| | 1 | 110 | | entity.HasOne(m => m.PairedAsset) |
| | 1 | 111 | | .WithMany() |
| | 1 | 112 | | .HasForeignKey(m => m.PairedAssetId) |
| | 1 | 113 | | .OnDelete(DeleteBehavior.SetNull); |
| | 1 | 114 | | |
| | 1 | 115 | | // N:1 with Burst |
| | 1 | 116 | | entity.HasOne(m => m.Burst) |
| | 1 | 117 | | .WithMany(b => b.Assets) |
| | 1 | 118 | | .HasForeignKey(m => m.BurstId) |
| | 1 | 119 | | .OnDelete(DeleteBehavior.SetNull); // Keeping the photo if the burst is dissolved |
| | 1 | 120 | | |
| | 1 | 121 | | // 1:N with ProxyFiles |
| | 1 | 122 | | entity.HasMany(m => m.ProxyFiles) |
| | 1 | 123 | | .WithOne(p => p.Asset) |
| | 1 | 124 | | .HasForeignKey(p => p.AssetId) |
| | 1 | 125 | | .OnDelete(DeleteBehavior.Cascade); |
| | 1 | 126 | | |
| | 1 | 127 | | // 1:N with Interactions |
| | 1 | 128 | | entity.HasMany(m => m.Interactions) |
| | 1 | 129 | | .WithOne(i => i.Asset) |
| | 1 | 130 | | .HasForeignKey(i => i.AssetId); |
| | 1 | 131 | | |
| | 1 | 132 | | // Partial index covering only active (non-deleted) assets |
| | 1 | 133 | | entity.HasIndex(m => m.IsSoftDeleted) |
| | 1 | 134 | | .HasFilter(@"""IsSoftDeleted"" = false") |
| | 1 | 135 | | .HasDatabaseName("IX_MediaAssets_Active"); |
| | 1 | 136 | | |
| | 1 | 137 | | // Global Query Filter: Hide soft-deleted files by default |
| | 1 | 138 | | entity.HasQueryFilter(m => !m.IsSoftDeleted); |
| | 1 | 139 | | |
| | 1 | 140 | | // Enum Conversion |
| | 1 | 141 | | entity.Property(m => m.MediaType).HasConversion<string>(); |
| | 1 | 142 | | }); |
| | | 143 | | |
| | 1 | 144 | | modelBuilder.Entity<Metadata>(entity => |
| | 1 | 145 | | { |
| | 1 | 146 | | entity.ToTable(t => t.HasComment( |
| | 1 | 147 | | "EXIF data, 1:1 with MediaAsset and keyed by it — there is no separate Id. " |
| | 1 | 148 | | + "Populated by ExifExtractionMiddleware; every field is best-effort, because a " |
| | 1 | 149 | | + "file may carry no EXIF at all." |
| | 1 | 150 | | )); |
| | 1 | 151 | | entity.Property(m => m.OrientationDegrees).HasComment( |
| | 1 | 152 | | "Rotation needed to display the image upright, already normalised from the raw " |
| | 1 | 153 | | + "EXIF orientation flag so consumers never interpret the flag themselves."); |
| | 1 | 154 | | entity.HasKey(m => m.AssetId); |
| | 1 | 155 | | |
| | 1 | 156 | | // 1:1 with MediaAsset |
| | 1 | 157 | | entity.HasOne(m => m.Asset) |
| | 1 | 158 | | .WithOne(a => a.Metadata) |
| | 1 | 159 | | .HasForeignKey<Metadata>(m => m.AssetId) |
| | 1 | 160 | | .OnDelete(DeleteBehavior.Cascade); |
| | 1 | 161 | | entity.HasQueryFilter(e => !e.Asset.IsSoftDeleted); |
| | 1 | 162 | | }); |
| | | 163 | | |
| | 1 | 164 | | modelBuilder.Entity<ProxyFile>(entity => |
| | 1 | 165 | | { |
| | 1 | 166 | | entity.ToTable(t => t.HasComment( |
| | 1 | 167 | | "One row per generated artefact on the local SSD. An asset has several. Written " |
| | 1 | 168 | | + "only by ProxyStagingWriter, at the moment the file reaches its final name." |
| | 1 | 169 | | )); |
| | 1 | 170 | | entity.Property(p => p.ProxyPath).HasComment( |
| | 1 | 171 | | "Path relative to the proxy root, sharded by CONTENT rather than by ingestion " |
| | 1 | 172 | | + "attempt so a retry overwrites its own debris instead of stranding it. " |
| | 1 | 173 | | + "IProxyDirectoryStrategy is the single place that rule lives."); |
| | 1 | 174 | | entity.Property(p => p.ProxyType).HasComment( |
| | 1 | 175 | | "Thumbnail, WebVideo, FullPreview or BlurHash, persisted as text. Note BlurHash " |
| | 1 | 176 | | + "is an ordinary proxy ROW whose content is a file — not a string column on the " |
| | 1 | 177 | | + "asset."); |
| | 1 | 178 | | |
| | 1 | 179 | | entity.HasIndex(p => p.AssetId); |
| | 1 | 180 | | entity.Property(p => p.ProxyType).HasConversion<string>(); |
| | 1 | 181 | | entity.HasQueryFilter(e => !e.Asset.IsSoftDeleted); |
| | 1 | 182 | | }); |
| | | 183 | | |
| | 1 | 184 | | modelBuilder.Entity<RefreshToken>(entity => |
| | 1 | 185 | | { |
| | 1 | 186 | | entity.ToTable(t => t.HasComment( |
| | 1 | 187 | | "Issued and revoked by the API; expired rows are swept by the Worker's " |
| | 1 | 188 | | + "TokenCleanupService. One of the few tables both services touch." |
| | 1 | 189 | | )); |
| | 1 | 190 | | entity.Property(r => r.TokenHash).HasComment( |
| | 1 | 191 | | "Hash, never the token itself — a database disclosure must not hand out usable " |
| | 1 | 192 | | + "sessions."); |
| | 1 | 193 | | |
| | 1 | 194 | | entity.HasIndex(r => r.TokenHash).IsUnique(); |
| | 1 | 195 | | entity.HasIndex(r => new { r.UserId, r.ExpiresAt }); |
| | 1 | 196 | | |
| | 1 | 197 | | entity.HasOne(r => r.User) |
| | 1 | 198 | | .WithMany(u => u.RefreshTokens) |
| | 1 | 199 | | .HasForeignKey(r => r.UserId) |
| | 1 | 200 | | .OnDelete(DeleteBehavior.Cascade); |
| | 1 | 201 | | }); |
| | | 202 | | |
| | 1 | 203 | | modelBuilder.Entity<Invite>(entity => |
| | 1 | 204 | | { |
| | 1 | 205 | | entity.ToTable(t => t.HasComment( |
| | 1 | 206 | | "Admin-issued registration tokens. Registration requires one; the first user " |
| | 1 | 207 | | + "(bootstrap admin) is exempt. Redemption is a read-then-write race, which is " |
| | 1 | 208 | | + "why this is the only table carrying a concurrency token." |
| | 1 | 209 | | )); |
| | 1 | 210 | | entity.Property(i => i.TokenHash).HasComment( |
| | 1 | 211 | | "Hash, never the token itself. 44 chars — base64 of a 32-byte value."); |
| | 1 | 212 | | |
| | 1 | 213 | | entity.HasIndex(i => i.TokenHash).IsUnique(); |
| | 1 | 214 | | entity.Property(i => i.TokenHash).HasMaxLength(44); |
| | 1 | 215 | | |
| | 1 | 216 | | // xmin is a Postgres system column incremented on every UPDATE. |
| | 1 | 217 | | // Npgsql recognises the "xmin" column name and excludes it from migrations. |
| | 1 | 218 | | entity.Property<uint>("xmin") |
| | 1 | 219 | | .HasColumnName("xmin") |
| | 1 | 220 | | .ValueGeneratedOnAddOrUpdate() |
| | 1 | 221 | | .IsConcurrencyToken(); |
| | 1 | 222 | | |
| | 1 | 223 | | entity.HasOne(i => i.CreatedBy) |
| | 1 | 224 | | .WithMany() |
| | 1 | 225 | | .HasForeignKey(i => i.CreatedByUserId) |
| | 1 | 226 | | .OnDelete(DeleteBehavior.SetNull); |
| | 1 | 227 | | |
| | 1 | 228 | | entity.HasOne(i => i.UsedBy) |
| | 1 | 229 | | .WithMany() |
| | 1 | 230 | | .HasForeignKey(i => i.UsedByUserId) |
| | 1 | 231 | | .OnDelete(DeleteBehavior.SetNull); |
| | 1 | 232 | | }); |
| | | 233 | | |
| | 1 | 234 | | modelBuilder.Entity<User>(entity => |
| | 1 | 235 | | { |
| | 1 | 236 | | entity.ToTable(t => t.HasComment( |
| | 1 | 237 | | "Owns storage configs and interactions. All identity writes happen in the API; " |
| | 1 | 238 | | + "the Worker only reads." |
| | 1 | 239 | | )); |
| | 1 | 240 | | entity.Property(u => u.PasswordHash).HasComment( |
| | 1 | 241 | | "Argon2id. The parameters live with the hasher, not here, so rotating them does " |
| | 1 | 242 | | + "not require a migration."); |
| | 1 | 243 | | entity.Property(u => u.MustChangePassword).HasComment( |
| | 1 | 244 | | "Set by an admin reset. MustChangePasswordMiddleware then 403s every route except " |
| | 1 | 245 | | + "the handful needed to change it."); |
| | 1 | 246 | | |
| | 1 | 247 | | entity.HasIndex(u => u.Username).IsUnique().HasDatabaseName(UserIndexNames.UsernameUnique); |
| | 1 | 248 | | entity.HasIndex(u => u.Email).IsUnique().HasDatabaseName(UserIndexNames.EmailUnique); |
| | 1 | 249 | | |
| | 1 | 250 | | // 1:N with StorageConfig |
| | 1 | 251 | | entity.HasMany(u => u.StorageConfigs) |
| | 1 | 252 | | .WithOne(s => s.User) |
| | 1 | 253 | | .HasForeignKey(s => s.UserId); |
| | 1 | 254 | | |
| | 1 | 255 | | // 1:N with Interactions |
| | 1 | 256 | | entity.HasMany(u => u.Interactions) |
| | 1 | 257 | | .WithOne(i => i.User) |
| | 1 | 258 | | .HasForeignKey(i => i.UserId); |
| | 1 | 259 | | }); |
| | | 260 | | |
| | 1 | 261 | | modelBuilder.Entity<UserStorageConfig>(entity => |
| | 1 | 262 | | { |
| | 1 | 263 | | entity.ToTable(t => t.HasComment( |
| | 1 | 264 | | "A NAS root assigned to one user. This is the boundary that scopes assets to a " |
| | 1 | 265 | | + "user and lets several Workers each monitor a separate config." |
| | 1 | 266 | | )); |
| | 1 | 267 | | entity.Property(s => s.RootPath).HasComment( |
| | 1 | 268 | | "GLOBALLY unique, not per user: a path cannot be assigned to two configs across " |
| | 1 | 269 | | + "all users. Two users indexing the same directory would duplicate every asset " |
| | 1 | 270 | | + "and let one user's config removal cascade away the other's rows."); |
| | 1 | 271 | | |
| | 1 | 272 | | entity.HasIndex(s => s.UserId); |
| | 1 | 273 | | entity.HasIndex(s => s.RootPath).IsUnique(); |
| | 1 | 274 | | |
| | 1 | 275 | | // 1:N with MediaAsset |
| | 1 | 276 | | entity.HasMany(s => s.Assets) |
| | 1 | 277 | | .WithOne(a => a.StorageConfig) |
| | 1 | 278 | | .HasForeignKey(a => a.StorageConfigId); |
| | 1 | 279 | | }); |
| | 1 | 280 | | } |
| | | 281 | | } |