Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Simplify StatusWorker logic to act as heartbeat only instead of controlling service status (#2159)
Leendert de Borst25bfab67a671
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260908153057_RemoveWorkerServiceStatusDesiredStatus.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260908153057_RemoveWorkerServiceStatusDesiredStatus.Designer.csnew file mode 100644index 000000000..34a3c0b1c--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260908153057_RemoveWorkerServiceStatusDesiredStatus.Designer.cs@@ -0,0 +1,2011 @@+// <auto-generated />+using System;+using AliasServerDb;+using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Infrastructure;+using Microsoft.EntityFrameworkCore.Migrations;+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;++#nullable disable++namespace AliasServerDb.Migrations+{+ [DbContext(typeof(AliasServerDbContext))]+ [Migration("20260908153057_RemoveWorkerServiceStatusDesiredStatus")]+ partial class RemoveWorkerServiceStatusDesiredStatus+ {+ /// <inheritdoc />+ protected override void BuildTargetModel(ModelBuilder modelBuilder)+ {+#pragma warning disable 612, 618+ modelBuilder+ .HasAnnotation("ProductVersion", "10.0.10")+ .HasAnnotation("Proxies:ChangeTracking", false)+ .HasAnnotation("Proxies:CheckEquality", false)+ .HasAnnotation("Proxies:LazyLoading", true)+ .HasAnnotation("Relational:MaxIdentifierLength", 63);++ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);++ modelBuilder.Entity("AliasServerDb.AdminUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastPasswordChanged")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AdminUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<bool>("Blocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("BlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastActivityDate")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<DateTime>("PasswordChangedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<Guid>("PersonalGroupId")+ .HasColumnType("uuid");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<string>("SrpIdentity")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("PersonalGroupId")+ .IsUnique()+ .HasDatabaseName("UX_AliasVaultUsers_PersonalGroupId");++ b.ToTable("AliasVaultUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("DeviceIdentifier")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("ExpireDate")+ .HasMaxLength(255)+ .HasColumnType("timestamp with time zone");++ b.Property<string>("IpAddress")+ .HasMaxLength(45)+ .HasColumnType("character varying(45)");++ b.Property<string>("PreviousTokenValue")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Value")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("AliasVaultUserRefreshTokens");+ });++ modelBuilder.Entity("AliasServerDb.AuthLog", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("AdditionalInfo")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Browser")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Client")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Country")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("DeviceType")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<int>("EventType")+ .HasColumnType("integer");++ b.Property<int?>("FailureReason")+ .HasColumnType("integer");++ b.Property<string>("IpAddress")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<bool>("IsSuccess")+ .HasColumnType("boolean");++ b.Property<bool>("IsSuspiciousActivity")+ .HasColumnType("boolean");++ b.Property<string>("OperatingSystem")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("RequestPath")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("Timestamp")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Username")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex(new[] { "EventType" }, "IX_EventType");++ b.HasIndex(new[] { "IpAddress" }, "IX_IpAddress");++ b.HasIndex(new[] { "Timestamp" }, "IX_Timestamp");++ b.HasIndex(new[] { "Username", "IsSuccess", "Timestamp" }, "IX_Username_IsSuccess_Timestamp")+ .IsDescending(false, false, true);++ b.HasIndex(new[] { "Username", "Timestamp" }, "IX_Username_Timestamp")+ .IsDescending(false, true);++ b.ToTable("AuthLogs");+ });++ modelBuilder.Entity("AliasServerDb.BlockedIpRange", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<bool>("BlockLogin")+ .HasColumnType("boolean");++ b.Property<bool>("BlockRegistration")+ .HasColumnType("boolean");++ b.Property<bool>("BlockShadow")+ .HasColumnType("boolean");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<string>("IpRange")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Reason")+ .HasMaxLength(500)+ .HasColumnType("character varying(500)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex(new[] { "Enabled" }, "IX_BlockedIpRange_Enabled");++ b.HasIndex(new[] { "IpRange" }, "IX_BlockedIpRange_IpRange")+ .IsUnique();++ b.ToTable("BlockedIpRanges");+ });++ modelBuilder.Entity("AliasServerDb.CapabilityRule", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("CapabilityKey")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("ClientName")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("EffectiveFrom")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime?>("EffectiveUntil")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<Guid?>("GroupId")+ .HasColumnType("uuid");++ b.Property<string>("Kind")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<string>("Notes")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Tier")+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Value")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("Tier");++ b.HasIndex("UserId");++ b.HasIndex("CapabilityKey", "Enabled");++ b.ToTable("CapabilityRules");+ });++ modelBuilder.Entity("AliasServerDb.ClientAction", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Payload")+ .HasColumnType("jsonb");++ b.Property<Guid?>("TargetGroupId")+ .HasColumnType("uuid");++ b.Property<string>("TargetUserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("TargetGroupId");++ b.HasIndex("TargetUserId");++ b.ToTable("ClientActions");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<int>("AttachmentCount")+ .HasColumnType("integer");++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("DateSystem")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("From")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageHtml")+ .HasColumnType("text");++ b.Property<string>("MessagePlain")+ .HasColumnType("text");++ b.Property<string>("MessagePreview")+ .HasColumnType("text");++ b.Property<string>("MessageSource")+ .HasColumnType("text");++ b.Property<byte[]>("MessageSourceBytes")+ .HasColumnType("bytea");++ b.Property<bool>("PushNotificationSent")+ .HasColumnType("boolean");++ b.Property<string>("Subject")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("To")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<bool>("Visible")+ .HasColumnType("boolean");++ b.HasKey("Id");++ b.HasIndex("Date");++ b.HasIndex("DateSystem");++ b.HasIndex("PushNotificationSent");++ b.HasIndex("Visible");++ b.HasIndex("To", "DateSystem");++ b.ToTable("Emails");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<byte[]>("Bytes")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<string>("Filename")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("Filesize")+ .HasColumnType("integer");++ b.Property<string>("MimeType")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("EmailId");++ b.ToTable("EmailAttachments");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Address")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressDomain")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressLocal")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("AnonymizedSenderCounted")+ .HasColumnType("boolean");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Address")+ .IsUnique();++ b.ToTable("EmailClaims");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.Property<Guid>("EmailClaimId")+ .HasColumnType("uuid");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.Property<string>("State")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.HasKey("EmailClaimId", "VaultManifestId");++ b.HasIndex("EmailClaimId")+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")+ .HasFilter("\"State\" <> 'Removed'");++ b.HasIndex("VaultManifestId", "EmailClaimId");++ b.ToTable("EmailClaimLinks");+ });++ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>+ {+ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<Guid>("VaultManifestDeliveryKeyId")+ .HasColumnType("uuid");++ b.Property<string>("EncryptedSymmetricKey")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");++ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");++ b.ToTable("EmailDecryptionKeys");+ });++ modelBuilder.Entity("AliasServerDb.EmailPart", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<byte[]>("Bytes")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<int>("PartIndex")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.HasIndex("EmailId", "PartIndex")+ .IsUnique();++ b.ToTable("EmailParts");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.PrimitiveCollection<int[]>("AnonymizedEmailAliasSenderCounts")+ .IsRequired()+ .ValueGeneratedOnAdd()+ .HasColumnType("integer[]")+ .HasDefaultValueSql("array_fill(0, ARRAY[64])");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailsReceived")+ .HasColumnType("integer");++ b.Property<int>("MaxEmailAgeDays")+ .HasColumnType("integer");++ b.Property<int>("MaxEmails")+ .HasColumnType("integer");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("ShadowBlocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("ShadowBlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("Type")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.ToTable("Groups");+ });++ modelBuilder.Entity("AliasServerDb.GroupInvitation", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedName")+ .HasColumnType("text");++ b.Property<string>("EncryptedVek")+ .HasColumnType("text");++ b.Property<Guid>("GroupId")+ .HasColumnType("uuid");++ b.Property<string>("InviteeUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("InviterUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("RespondedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("Role")+ .HasColumnType("integer");++ b.Property<string>("State")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("UserGrantKeyId")+ .HasColumnType("uuid");++ b.Property<int>("VaultKeyVersion")+ .HasColumnType("integer");++ b.Property<Guid?>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("InviterUserId");++ b.HasIndex("UserGrantKeyId");++ b.HasIndex("InviteeUserId", "State");++ b.HasIndex("VaultManifestId", "InviteeUserId")+ .IsUnique()+ .HasDatabaseName("UX_GroupInvitations_Manifest_Invitee_Pending")+ .HasFilter("\"State\" = 'Pending'");++ b.ToTable("GroupInvitations");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("Role")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.HasIndex("GroupId", "UserId")+ .IsUnique();++ b.ToTable("GroupMembers");+ });++ modelBuilder.Entity("AliasServerDb.Log", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("Application")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Exception")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Level")+ .IsRequired()+ .HasMaxLength(128)+ .HasColumnType("character varying(128)");++ b.Property<string>("LogEvent")+ .IsRequired()+ .HasColumnType("text")+ .HasColumnName("LogEvent");++ b.Property<string>("Message")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageTemplate")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Properties")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("SourceContext")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("TimeStamp")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Application");++ b.HasIndex("TimeStamp");++ b.ToTable("Logs", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime?>("ClearedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ClientIpAddress")+ .HasColumnType("text");++ b.Property<string>("ClientPublicKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedDecryptionKey")+ .HasColumnType("text");++ b.Property<DateTime?>("FulfilledAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("MobileIpAddress")+ .HasColumnType("text");++ b.Property<DateTime?>("RetrievedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex(new[] { "ClientIpAddress" }, "IX_ClientIpAddress");++ b.HasIndex(new[] { "CreatedAt" }, "IX_CreatedAt");++ b.HasIndex(new[] { "MobileIpAddress" }, "IX_MobileIpAddress");++ b.HasIndex(new[] { "RetrievedAt", "ClearedAt", "FulfilledAt" }, "IX_RetrievedAt_ClearedAt_FulfilledAt");++ b.HasIndex(new[] { "UserId" }, "IX_UserId");++ b.ToTable("MobileLoginRequests");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AppliesToAccountAgeMaxDays")+ .HasColumnType("integer");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("EffectiveFrom")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime?>("EffectiveUntil")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<Guid?>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("LimitType")+ .HasColumnType("integer");++ b.Property<int>("MaxCount")+ .HasColumnType("integer");++ b.Property<string>("Notes")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<int?>("Tier")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("WindowSeconds")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("Tier");++ b.HasIndex("LimitType", "Enabled");++ b.ToTable("RateLimits");+ });++ modelBuilder.Entity("AliasServerDb.ServerSetting", b =>+ {+ b.Property<string>("Key")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("Key");++ b.ToTable("ServerSettings");+ });++ modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<TimeOnly?>("EndTime")+ .HasColumnType("time without time zone");++ b.Property<string>("ErrorMessage")+ .HasColumnType("text");++ b.Property<bool>("IsOnDemand")+ .HasColumnType("boolean");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("RunDate")+ .HasColumnType("timestamp with time zone");++ b.Property<TimeOnly>("StartTime")+ .HasColumnType("time without time zone");++ b.Property<int>("Status")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.ToTable("TaskRunnerJobs");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedPrivateKey")+ .IsRequired()+ .HasMaxLength(4000)+ .HasColumnType("character varying(4000)");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId")+ .IsUnique()+ .HasDatabaseName("UX_UserGrantKeys_User_Primary")+ .HasFilter("\"IsPrimary\"");++ b.ToTable("UserGrantKeys");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedAccountKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Label")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId", "Type", "Label")+ .IsUnique()+ .HasDatabaseName("UX_UserUnlockKeys_UserId_Type_Label");++ b.ToTable("UserUnlockKeys");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKeysHistory", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("ArchivedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ArchivedByClient")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedAccountKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Label")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<Guid>("UnlockKeyId")+ .HasColumnType("uuid");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("ArchivedAt")+ .HasDatabaseName("IX_UserUnlockKeysHistory_ArchivedAt");++ b.HasIndex("UserId", "Type", "ArchivedAt")+ .HasDatabaseName("IX_UserUnlockKeysHistory_UserId_Type_ArchivedAt");++ b.ToTable("UserUnlockKeysHistory", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.Property<string>("Hash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("OwnerUserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Category")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<int>("SizeBytes")+ .HasColumnType("integer");++ b.HasKey("Hash", "OwnerUserId");++ b.HasIndex("OwnerUserId", "Category");++ b.ToTable("VaultBlobObjects");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("BlobHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.HasKey("ManifestId", "RevisionNumber", "BlobHash");++ b.ToTable("VaultBlobReferences");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category");++ b.ToTable("VaultDataBuckets");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category", "RevisionNumber");++ b.ToTable("VaultDataBucketsHistory");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.Property<Guid>("ManifestId")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<byte[]>("ManifestBlob")+ .HasColumnType("bytea");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<Guid>("OwnerGroupId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId");++ b.HasIndex("OwnerGroupId");++ b.ToTable("VaultManifests");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedVek")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("UserGrantKeyId")+ .HasColumnType("uuid");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("UserGrantKeyId");++ b.HasIndex("VaultManifestId")+ .HasDatabaseName("IX_VaultManifestAccessKeys_VaultManifestId");++ b.HasIndex("UserId", "Type", "VaultManifestId", "KeyVersion")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestAccessKeys_UserId_Type_Manifest_Version");++ b.ToTable("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("VaultManifestId")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestDeliveryKeys_Manifest_Primary")+ .HasFilter("\"IsPrimary\"");++ b.HasIndex("VaultManifestId", "IsPrimary");++ b.ToTable("VaultManifestDeliveryKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<byte[]>("ManifestBlob")+ .HasColumnType("bytea");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId", "RevisionNumber");++ b.ToTable("VaultManifestsHistory", (string)null);+ });++ modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("CurrentStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("Heartbeat")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ServiceName")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.ToTable("WorkerServiceStatuses");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("FriendlyName")+ .HasColumnType("text");++ b.Property<string>("Xml")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("DataProtectionKeys");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("ClaimType")+ .HasColumnType("text");++ b.Property<string>("ClaimValue")+ .HasColumnType("text");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("UserClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("text");++ b.Property<string>("LoginProvider")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("UserId", "LoginProvider", "Name");++ b.ToTable("UserTokens", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.HasOne("AliasServerDb.Group", "PersonalGroup")+ .WithOne()+ .HasForeignKey("AliasServerDb.AliasVaultUser", "PersonalGroupId")+ .OnDelete(DeleteBehavior.Restrict)+ .IsRequired();++ b.Navigation("PersonalGroup");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.CapabilityRule", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("Group");++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.ClientAction", b =>+ {+ b.HasOne("AliasServerDb.Group", "TargetGroup")+ .WithMany()+ .HasForeignKey("TargetGroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.HasOne("AliasServerDb.AliasVaultUser", "TargetUser")+ .WithMany()+ .HasForeignKey("TargetUserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("TargetGroup");++ b.Navigation("TargetUser");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Attachments")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.HasOne("AliasServerDb.EmailClaim", "EmailClaim")+ .WithMany("Links")+ .HasForeignKey("EmailClaimId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("EmailClaim");++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("DecryptionKeys")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")+ .WithMany("DecryptionKeys")+ .HasForeignKey("VaultManifestDeliveryKeyId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired()+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId");++ b.Navigation("Email");++ b.Navigation("VaultManifestDeliveryKey");+ });++ modelBuilder.Entity("AliasServerDb.EmailPart", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Parts")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.GroupInvitation", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "Invitee")+ .WithMany()+ .HasForeignKey("InviteeUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "Inviter")+ .WithMany()+ .HasForeignKey("InviterUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.UserGrantKey", "UserGrantKey")+ .WithMany()+ .HasForeignKey("UserGrantKeyId")+ .OnDelete(DeleteBehavior.SetNull);++ b.Navigation("Group");++ b.Navigation("Invitee");++ b.Navigation("Inviter");++ b.Navigation("UserGrantKey");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany("Members")+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Group");++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("Group");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKeysHistory", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("OwnerUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultDataBucket", "Bucket")+ .WithMany()+ .HasForeignKey("ManifestId", "Category")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Bucket");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.HasOne("AliasServerDb.Group", "OwnerGroup")+ .WithMany()+ .HasForeignKey("OwnerGroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("OwnerGroup");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.HasOne("AliasServerDb.UserGrantKey", "UserGrantKey")+ .WithMany()+ .HasForeignKey("UserGrantKeyId")+ .OnDelete(DeleteBehavior.SetNull);++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("VaultManifestAccessKeys")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");++ b.Navigation("UserGrantKey");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Navigation("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Navigation("Attachments");++ b.Navigation("DecryptionKeys");++ b.Navigation("Parts");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Navigation("Links");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Navigation("Members");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Navigation("DecryptionKeys");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260908153057_RemoveWorkerServiceStatusDesiredStatus.cs b/apps/server/Databases/AliasServerDb/Migrations/20260908153057_RemoveWorkerServiceStatusDesiredStatus.csnew file mode 100644index 000000000..0de185b1d--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260908153057_RemoveWorkerServiceStatusDesiredStatus.cs@@ -0,0 +1,30 @@+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace AliasServerDb.Migrations+{+ /// <inheritdoc />+ public partial class RemoveWorkerServiceStatusDesiredStatus : Migration+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.DropColumn(+ name: "DesiredStatus",+ table: "WorkerServiceStatuses");+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.AddColumn<string>(+ name: "DesiredStatus",+ table: "WorkerServiceStatuses",+ type: "character varying(50)",+ maxLength: 50,+ nullable: false,+ defaultValue: "");+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex dc3d7f02a..c7abb6d44 100644--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -1583,11 +1583,6 @@ namespace AliasServerDb.Migrations.HasMaxLength(50).HasColumnType("character varying(50)");- b.Property<string>("DesiredStatus")- .IsRequired()- .HasMaxLength(50)- .HasColumnType("character varying(50)");-b.Property<DateTime>("Heartbeat").HasColumnType("timestamp with time zone");diff --git a/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/StatusWorkerResilienceTestHostBuilder.cs b/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/StatusWorkerResilienceTestHostBuilder.csindex 780b46af3..ce84c4f70 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/StatusWorkerResilienceTestHostBuilder.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/StatusWorkerResilienceTestHostBuilder.cs@@ -17,8 +17,8 @@ using Microsoft.Extensions.Hosting;/// <summary>/// Builds a test host whose StatusWorker is backed by a database context that injects a transient-/// <see cref="TaskCanceledException"/> on its first few save operations to test if the StatusWorker-/// recovers itself instead of permanently soft-stopping the service.+/// <see cref="TaskCanceledException"/> on its first few save operations to test that the StatusWorker+/// keeps heartbeating and still reaches the Started state./// </summary>public class StatusWorkerResilienceTestHostBuilder : AbstractTestHostBuilder{diff --git a/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/TestHostBuilder.cs b/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/TestHostBuilder.csindex 86b9c2eef..e0c91013d 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/TestHostBuilder.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/Helpers/TestHostBuilder.cs@@ -16,9 +16,8 @@ using Microsoft.Extensions.Hosting;/// against it. This primarily tests basic functionality of the hosted service such as starting, stopping and error/// handling.///-/// The StatusHostedService is a wrapper around the HostedService class that provides additional functionality for-/// managing the status of the hosted service. This includes being able to start and stop the services from the-/// AliasVault admin panel.+/// The StatusHostedService is a wrapper around the HostedService class that keeps the wrapped service running and+/// reports its liveness through the heartbeat record shown in the AliasVault admin panel./// </summary>public class TestHostBuilder : AbstractTestHostBuilder{diff --git a/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/StatusWorkerResilienceTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/StatusWorkerResilienceTests.csindex fdec963c3..cd9df8a44 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/StatusWorkerResilienceTests.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/StatusHostedService/StatusWorkerResilienceTests.cs@@ -13,8 +13,8 @@ using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Hosting;/// <summary>-/// Regression tests ensuring the StatusWorker recovers itself when a exception is thrown-/// inside the worker logic.+/// Regression tests ensuring the StatusWorker keeps heartbeating when an exception is thrown+/// inside its database calls./// </summary>[TestFixture]public class StatusWorkerResilienceTests@@ -52,11 +52,11 @@ public class StatusWorkerResilienceTests}/// <summary>- /// Verifies that the StatusWorker recovers itself when a exception is thrown inside the worker logic.+ /// Verifies that the StatusWorker reaches the Started state after transient database faults instead of getting stuck./// </summary>/// <returns>Task.</returns>[Test]- public async Task ExceptionThrownInsideWorkerLogicDoesNotSoftStopService()+ public async Task TransientDatabaseFaultDoesNotStopHeartbeat(){await _testHost.StartAsync();@@ -78,6 +78,6 @@ public class StatusWorkerResilienceTestsawait Task.Delay(1000);}- Assert.That(currentStatus, Is.EqualTo("Started"), "Service should recover to Started after a exception is thrown inside the worker logic instead of remaining soft-stopped.");+ Assert.That(currentStatus, Is.EqualTo("Started"), "Service should reach Started after transient database faults inside the StatusWorker.");}}diff --git a/apps/server/Utilities/AliasVault.WorkerStatus/Database/WorkerServiceStatus.cs b/apps/server/Utilities/AliasVault.WorkerStatus/Database/WorkerServiceStatus.csindex 54e07a644..f47803bbb 100644--- a/apps/server/Utilities/AliasVault.WorkerStatus/Database/WorkerServiceStatus.cs+++ b/apps/server/Utilities/AliasVault.WorkerStatus/Database/WorkerServiceStatus.cs@@ -1,4 +1,4 @@-//-----------------------------------------------------------------------+//-----------------------------------------------------------------------// <copyright file="WorkerServiceStatus.cs" company="aliasvault">// Copyright (c) aliasvault. All rights reserved.// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.@@ -8,10 +8,9 @@namespace AliasVault.WorkerStatus.Database;using System.ComponentModel.DataAnnotations;-using System.ComponentModel.DataAnnotations.Schema;/// <summary>-/// Represents the status of a worker service for monitoring and control.+/// Heartbeat record of a worker service, used to tell whether the service is alive and healthy./// </summary>public class WorkerServiceStatus{@@ -28,17 +27,11 @@ public class WorkerServiceStatuspublic string ServiceName { get; set; } = null!;/// <summary>- /// Gets or sets the current status of the service.+ /// Gets or sets the current status of the service, one of the <see cref="Status"/> names./// </summary>[StringLength(50)]public string CurrentStatus { get; set; } = null!;- /// <summary>- /// Gets or sets the desired status of the service.- /// </summary>- [StringLength(50)]- public string DesiredStatus { get; set; } = null!;-/// <summary>/// Gets or sets the last heartbeat timestamp of the service./// </summary>diff --git a/apps/server/Utilities/AliasVault.WorkerStatus/Extensions/StatusExtensions.cs b/apps/server/Utilities/AliasVault.WorkerStatus/Extensions/StatusExtensions.csdeleted file mode 100644index 245bafc67..000000000--- a/apps/server/Utilities/AliasVault.WorkerStatus/Extensions/StatusExtensions.cs+++ /dev/null@@ -1,25 +0,0 @@-// ------------------------------------------------------------------------// <copyright file="StatusExtensions.cs" company="aliasvault">-// Copyright (c) aliasvault. All rights reserved.-// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.-// </copyright>-// -------------------------------------------------------------------------namespace AliasVault.WorkerStatus.Extensions;--/// <summary>-/// Extension methods for the Status enum.-/// </summary>-internal static class StatusExtensions-{- /// <summary>- /// String to Status enum conversion.- /// </summary>- /// <param name="status">Status enum.</param>- /// <returns>String as status enum.</returns>- /// <exception cref="ArgumentException">Thrown if string is not a known status enum.</exception>- public static Status ToStatusEnum(this string status)- {- return Enum.TryParse(status, out Status result) ? result : throw new ArgumentException("Invalid status value");- }-}diff --git a/apps/server/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.cs b/apps/server/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.csindex 8c1bff4db..c89cf2b29 100644--- a/apps/server/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.cs+++ b/apps/server/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.cs@@ -10,35 +10,17 @@ namespace AliasVault.WorkerStatus;using System.Collections.Concurrent;/// <summary>-/// Global service status class for monitoring and control.+/// In-process registry of the workers that make up one service and whether each is currently running./// </summary>-public class GlobalServiceStatus+/// <param name="serviceName">Name of the service that we are keeping track of.</param>+public class GlobalServiceStatus(string serviceName){private readonly ConcurrentDictionary<string, bool> _workerStatuses = new();/// <summary>- /// Initializes a new instance of the <see cref="GlobalServiceStatus"/> class.+ /// Gets the service name that identifies the service and its workers in the database./// </summary>- /// <param name="serviceName">Name of the service that we are keeping track of.</param>- public GlobalServiceStatus(string serviceName)- {- ServiceName = serviceName;- }-- /// <summary>- /// Gets or sets the status of the service.- /// </summary>- public string Status { get; set; } = "Stopped";-- /// <summary>- /// Gets or sets the current status of the service.- /// </summary>- public string CurrentStatus { get; set; } = "Stopped";-- /// <summary>- /// Gets or sets the ServiceName in order to identify the service and its workers in the database.- /// </summary>- public string ServiceName { get; set; }+ public string ServiceName { get; } = serviceName;/// <summary>/// Register a worker with the service.@@ -50,7 +32,7 @@ public class GlobalServiceStatus}/// <summary>- /// Set the status of a worker.+ /// Set the running state of a worker./// </summary>/// <param name="workerName">Name of the worker.</param>/// <param name="isRunning">Boolean which indicates if worker is currently running.</param>@@ -63,14 +45,8 @@ public class GlobalServiceStatus}/// <summary>- /// Returns boolean indicating if all workers are running.- /// </summary>- /// <returns>Boolean which indicates if all workers are started.</returns>- public bool AreAllWorkersRunning() => _workerStatuses.All(w => w.Value);-- /// <summary>- /// Returns boolean indicating if all workers are stopped.+ /// Returns boolean indicating if all registered workers are running./// </summary>- /// <returns>Boolean which indicates if all workers are stopped.</returns>- public bool AreAllWorkersStopped() => _workerStatuses.All(w => !w.Value);+ /// <returns>Boolean which indicates if all workers are running.</returns>+ public bool AreAllWorkersRunning() => !_workerStatuses.IsEmpty && _workerStatuses.All(w => w.Value);}diff --git a/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/ServiceCollectionExtensions.cs b/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/ServiceCollectionExtensions.csindex 84f638cb3..b920b8111 100644--- a/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/ServiceCollectionExtensions.cs+++ b/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/ServiceCollectionExtensions.cs@@ -19,13 +19,12 @@ using Microsoft.Extensions.Hosting;public static class ServiceCollectionExtensions{/// <summary>- /// Add a HostedService that is monitored by the StatusWorker.+ /// Add a HostedService whose liveness is reported by the StatusWorker heartbeat./// </summary>/// <param name="services">IServiceCollection.</param>/// <typeparam name="TWorker">Worker type to add.</typeparam>- /// <typeparam name="TContext">DBContext type to use for persisting and retrieving the status data.</typeparam>- /// <param name="serviceName">The unique service name through which the worker processes- /// can be triggered to start or stop.</param>+ /// <typeparam name="TContext">DBContext type to use for persisting the heartbeat record.</typeparam>+ /// <param name="serviceName">The unique service name under which the heartbeat record is stored.</param>/// <returns>IServiceCollection instance.</returns>public static IServiceCollection AddStatusHostedService<TWorker, TContext>(this IServiceCollection services, string serviceName)where TWorker : class, IHostedServicediff --git a/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/StatusHostedService.cs b/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/StatusHostedService.csindex d234e15ba..94c55c769 100644--- a/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/StatusHostedService.cs+++ b/apps/server/Utilities/AliasVault.WorkerStatus/ServiceExtensions/StatusHostedService.cs@@ -7,20 +7,19 @@namespace AliasVault.WorkerStatus.ServiceExtensions;-using AliasVault.WorkerStatus.Extensions;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;/// <summary>-/// StatusHostedService class.+/// Runs an inner hosted service, reports whether it is running to the <see cref="GlobalServiceStatus"/>+/// registry and restarts it with exponential backoff when it faults./// </summary>-/// <typeparam name="T">The HostedService to add.</typeparam>+/// <typeparam name="T">The HostedService to wrap.</typeparam>public class StatusHostedService<T>(ILogger<StatusHostedService<T>> logger, GlobalServiceStatus globalServiceStatus, T innerService) : BackgroundServicewhere T : IHostedService{/// <summary>- /// A minimum delay that is used to wait before restarting the worker after a fault in the innerService.- /// This delay is increased exponentially with a maximum delay of <see cref="_restartMaxDelayInMs"/>.+ /// Initial delay before restarting the worker after a fault. Doubles on every consecutive fault up to <see cref="_restartMaxDelayInMs"/>./// </summary>private const int _restartMinDelayInMs = 1000;@@ -30,59 +29,75 @@ public class StatusHostedService<T>(ILogger<StatusHostedService<T>> logger, Globprivate const int _restartMaxDelayInMs = 3600000;/// <summary>- /// Lock object to prevent multiple tasks from starting the worker at the same time.+ /// A worker that stayed up at least this long before faulting resets the backoff to <see cref="_restartMinDelayInMs"/>./// </summary>- private readonly object _taskLock = new();+ private static readonly TimeSpan _healthyRunResetThreshold = TimeSpan.FromMinutes(1);/// <summary>/// Current delay before restarting the worker./// </summary>private int _restartDelayInMs = _restartMinDelayInMs;- /// <summary>- /// Default entry point called by the host.- /// </summary>- /// <param name="stoppingToken">Cancellation token.</param>- /// <returns>Task.</returns>+ /// <inheritdoc />protected override async Task ExecuteAsync(CancellationToken stoppingToken){- logger.LogInformation("StatusHostedService<{ServiceType}> ExecuteAsync called.", typeof(T).Name);+ var workerName = typeof(T).Name;+ logger.LogInformation("StatusHostedService<{ServiceType}> ExecuteAsync called.", workerName);- // Register the service with the global service status so the StatusWorker will monitor it.- globalServiceStatus.RegisterWorker(typeof(T).Name);+ // Register the worker so the StatusWorker includes it in the service heartbeat.+ globalServiceStatus.RegisterWorker(workerName);while (!stoppingToken.IsCancellationRequested){+ var startedAt = DateTime.UtcNow;try{- // Start the inner while loop with the second cancellationToken.- await ExecuteInnerAsync(stoppingToken);+ globalServiceStatus.SetWorkerStatus(workerName, true);+ await CallExecuteAsync(innerService, stoppingToken);}catch (OperationCanceledException ex) when (stoppingToken.IsCancellationRequested){// Genuine host shutdown, exit the loop gracefully.- logger.LogInformation(ex, "StatusHostedService<{ServiceType}> is stopping due to a cancellation request.", typeof(T).Name);+ logger.LogInformation(ex, "StatusHostedService<{ServiceType}> is stopping due to a cancellation request.", workerName);break;}catch (Exception ex){- // Any other exception should not break the loop but instead log the error- // and let the restart logic below retry the worker.- logger.LogError(ex, "An error occurred in StatusHostedService<{ServiceType}>", typeof(T).Name);+ // Any other exception (including cancellations not caused by the host) is logged and the worker restarted below.+ logger.LogError(ex, "An error occurred in StatusHostedService<{ServiceType}>", workerName);}finally{- if (!stoppingToken.IsCancellationRequested)- {- // If the parent service was not stopped, wait for a second before attempting to restart the worker.- await Task.Delay(1000, stoppingToken);- }+ globalServiceStatus.SetWorkerStatus(workerName, false);+ }++ if (stoppingToken.IsCancellationRequested)+ {+ break;+ }++ if (DateTime.UtcNow - startedAt >= _healthyRunResetThreshold)+ {+ _restartDelayInMs = _restartMinDelayInMs;+ }++ logger.LogWarning("StatusHostedService<{ServiceType}> stopped at: {Time}, restarting in {Delay} ms.", workerName, DateTimeOffset.Now, _restartDelayInMs);++ try+ {+ await Task.Delay(_restartDelayInMs, stoppingToken);+ }+ catch (OperationCanceledException)+ {+ break;}++ _restartDelayInMs = Math.Min(_restartDelayInMs * 2, _restartMaxDelayInMs);}}/// <summary>- /// Calls the ExecuteAsync method of the inner service.+ /// Runs the inner service until it completes or throws./// </summary>/// <param name="innerService">The inner service.</param>/// <param name="cancellationToken">Cancellation token.</param>@@ -90,127 +105,16 @@ public class StatusHostedService<T>(ILogger<StatusHostedService<T>> logger, Glob{if (innerService is BackgroundService backgroundService){+ // The inner service is not registered as a hosted service itself, so invoke its protected ExecuteAsync directly.var executeMethod = backgroundService.GetType().GetMethod("ExecuteAsync", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);- var executionTask = (Task)executeMethod!.Invoke(backgroundService, new object[] { cancellationToken })!;-- // Wait for the ExecuteAsync method to complete or throw.+ var executionTask = (Task)executeMethod!.Invoke(backgroundService, [cancellationToken])!;await executionTask;}else{- // For non-BackgroundService implementations, start the service as normal and wait indefinitely+ // For non-BackgroundService implementations, start the service as normal and wait until the host stops.await innerService.StartAsync(cancellationToken);-- // For non-BackgroundService implementations, just wait indefinitelyawait Task.Delay(Timeout.Infinite, cancellationToken);}}-- /// <summary>- /// Start the inner while loop which adds a second cancellationToken that is controlled by the StatusWorker.- /// </summary>- /// <param name="cancellationToken">Cancellation token.</param>- private async Task ExecuteInnerAsync(CancellationToken cancellationToken)- {- Task? workerTask = null;-- // Add a second cancellationToken linked to the parent cancellation token.- // When the parent gets canceled this gets canceled as well. However, this one can also- // be canceled with a signal from the StatusWorker.- using var workerCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);-- while (!workerCancellationTokenSource.IsCancellationRequested)- {- if (globalServiceStatus.CurrentStatus.ToStatusEnum() == Status.Started || globalServiceStatus.CurrentStatus.ToStatusEnum() == Status.Starting)- {- lock (_taskLock)- {- if (workerTask == null)- {- workerTask = Task.Run(() => WorkerLogic(workerCancellationTokenSource.Token), workerCancellationTokenSource.Token);- }- }- }- else if (globalServiceStatus.CurrentStatus.ToStatusEnum() == Status.Stopping)- {- // If the StatusWorker has given us the signal to stop, cancel the inner worker.- await workerCancellationTokenSource.CancelAsync();- globalServiceStatus.SetWorkerStatus(typeof(T).Name, false);- }- else if (globalServiceStatus.CurrentStatus.ToStatusEnum() == Status.Stopped)- {- // Do nothing, the worker is stopped.- globalServiceStatus.SetWorkerStatus(typeof(T).Name, false);- }-- // Wait for a second before checking the status again.- await Task.Delay(1000, cancellationToken);- }-- // If we get here, cancel the worker task if it is still running.- await workerCancellationTokenSource.CancelAsync();- }-- /// <summary>- /// The worker logic that is executed by the inner service. This wraps the actual inner service logic- /// in a try/catch block to catch any exceptions and to set the worker status to false when the worker stops.- /// </summary>- /// <param name="cancellationToken">Cancellation token.</param>- private async Task WorkerLogic(CancellationToken cancellationToken)- {- while (!cancellationToken.IsCancellationRequested)- {- try- {- globalServiceStatus.SetWorkerStatus(typeof(T).Name, true);-- // If the inner service is a BackgroundService, listen for the results via reflection.- await CallExecuteAsync(innerService, cancellationToken);- }- catch (OperationCanceledException ex)- {- // Expected so we only log information.- logger.LogInformation(ex, "StatusHostedService<{ServiceType}> is stopping due to a cancellation request.", typeof(T).Name);- break;- }- catch (Exception ex)- {- logger.LogError(ex, "An error occurred in StatusHostedService<{ServiceType}>", typeof(T).Name);-- // If service is explicitly stopped, break out of the loop immediately.- if (cancellationToken.IsCancellationRequested)- {- break;- }- }- finally- {- logger.LogWarning("StatusHostedService<{ServiceType}> stopped at: {Time}", typeof(T).Name, DateTimeOffset.Now);-- // Reset the delay when the service is explicitly stopped- if (cancellationToken.IsCancellationRequested)- {- _restartDelayInMs = _restartMinDelayInMs;- }- }-- if (cancellationToken.IsCancellationRequested)- {- return;- }-- try- {- // If an exception occurred, delay with exponential backoff with a maximum before retrying.- await Task.Delay(_restartDelayInMs, cancellationToken);- _restartDelayInMs = Math.Min(_restartDelayInMs * 2, _restartMaxDelayInMs);- }- catch (OperationCanceledException)- {- // Reset delay on cancellation- _restartDelayInMs = _restartMinDelayInMs;- return;- }- }- }}diff --git a/apps/server/Utilities/AliasVault.WorkerStatus/Status.cs b/apps/server/Utilities/AliasVault.WorkerStatus/Status.csindex b4a99063b..0742da649 100644--- a/apps/server/Utilities/AliasVault.WorkerStatus/Status.cs+++ b/apps/server/Utilities/AliasVault.WorkerStatus/Status.cs@@ -8,27 +8,22 @@namespace AliasVault.WorkerStatus;/// <summary>-/// Enumeration of possible statuses for a worker service.+/// Lifecycle states a worker service reports through its heartbeat record./// </summary>public enum Status{/// <summary>- /// Indicates that the worker service has started.- /// </summary>- Started,-- /// <summary>- /// Indicates that the worker service is starting.+ /// The host is up but not all workers are running (yet, or after a worker fault while it restarts)./// </summary>Starting,/// <summary>- /// Indicates that the worker service is stopping.+ /// All workers are running./// </summary>- Stopping,+ Started,/// <summary>- /// Indicates that the worker service has stopped.+ /// The host shut down gracefully./// </summary>Stopped,}diff --git a/apps/server/Utilities/AliasVault.WorkerStatus/StatusWorker.cs b/apps/server/Utilities/AliasVault.WorkerStatus/StatusWorker.csindex 996dc9fc1..68563aaa1 100644--- a/apps/server/Utilities/AliasVault.WorkerStatus/StatusWorker.cs+++ b/apps/server/Utilities/AliasVault.WorkerStatus/StatusWorker.cs@@ -8,204 +8,89 @@namespace AliasVault.WorkerStatus;using AliasVault.WorkerStatus.Database;-using AliasVault.WorkerStatus.Extensions;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;/// <summary>-/// StatusWorker class for monitoring and controlling the status of individual worker services through a database.+/// Periodically writes a heartbeat record for the service to the database for tracking status in the admin UI./// </summary>public class StatusWorker(ILogger<StatusWorker> logger, Func<IWorkerStatusDbContext> createDbContext, GlobalServiceStatus globalServiceStatus) : BackgroundService{- private IWorkerStatusDbContext _dbContext = null!;-/// <summary>- /// Worker service execution method.+ /// Interval between two heartbeats in milliseconds./// </summary>- /// <param name="stoppingToken">CancellationToken.</param>- /// <returns>Task.</returns>+ private const int _heartbeatIntervalInMs = 5000;++ /// <inheritdoc />protected override async Task ExecuteAsync(CancellationToken stoppingToken){- try- {- using var initDbContext = createDbContext();- _dbContext = initDbContext;- await GetOrCreateInitialStatusRecordAsync();- }- catch (Exception e)- {- logger.LogError(e, "Failed to initialize service status record for {ServiceName}", globalServiceStatus.ServiceName);- }-while (!stoppingToken.IsCancellationRequested){- using var dbContext = createDbContext();- _dbContext = dbContext;-try{- var statusEntry = await GetServiceStatus();-- switch (statusEntry.CurrentStatus.ToStatusEnum())- {- case Status.Started:- // Ensure that all workers are running, if not, revert to "Starting" CurrentStatus.- await HandleStartedStatus(statusEntry);- break;- case Status.Starting:- await HandleStartingStatus(statusEntry);- break;- case Status.Stopping:- await HandleStoppingStatus(statusEntry);- break;- case Status.Stopped:- logger.LogInformation("Service is (soft) stopped.");- break;- }-- await Task.Delay(5000, stoppingToken);+ await WriteHeartbeatAsync(globalServiceStatus.AreAllWorkersRunning() ? Status.Started : Status.Starting);}- catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)+ catch (Exception e){- // Genuine host shutdown, exit the loop gracefully.- break;+ // A failed heartbeat (database timeout, cancellation, ...) is logged and retried on the next interval.+ logger.LogError(e, "Failed to write heartbeat for {ServiceName}", globalServiceStatus.ServiceName);}- catch (Exception e)++ try{- // Any other exception including database cancellations/timeouts should not break the loop but instead log the error- // and let the restart logic below retry the worker.- logger.LogError(e, "StatusWorker exception");- await Task.Delay(5000, stoppingToken);+ await Task.Delay(_heartbeatIntervalInMs, stoppingToken);+ }+ catch (OperationCanceledException)+ {+ break;}}try{- using var dbContext = createDbContext();- _dbContext = dbContext;- await SetServiceStatus(await GetServiceStatus(), "Stopped");+ await WriteHeartbeatAsync(Status.Stopped);}catch (Exception e){- logger.LogError(e, "Failed to set service status to Stopped during shutdown");- }- }-- /// <summary>- /// Handles the Started status.- /// </summary>- /// <param name="statusEntry">The WorkerServiceStatus entry.</param>- /// <returns>Task.</returns>- private async Task HandleStartedStatus(WorkerServiceStatus statusEntry)- {- if (!globalServiceStatus.AreAllWorkersRunning())- {- await SetServiceStatus(statusEntry, Status.Starting.ToString());- logger.LogInformation("Status was set to Started but not all workers are running (yet). Reverting to Starting.");- }- }-- /// <summary>- /// Handles the Starting status.- /// </summary>- /// <param name="statusEntry">The WorkerServiceStatus entry.</param>- /// <returns>Task.</returns>- private async Task HandleStartingStatus(WorkerServiceStatus statusEntry)- {- if (globalServiceStatus.AreAllWorkersRunning())- {- await SetServiceStatus(statusEntry, Status.Started.ToString());- logger.LogInformation("All workers started.");- }- else- {- logger.LogInformation("Waiting for all workers to start.");+ logger.LogError(e, "Failed to set service status to Stopped during shutdown for {ServiceName}", globalServiceStatus.ServiceName);}}/// <summary>- /// Handles the Stopping status.+ /// Writes the given status and the current time to the heartbeat record of the service./// </summary>- /// <param name="statusEntry">The WorkerServiceStatus entry.</param>- /// <returns>Task.</returns>- private async Task HandleStoppingStatus(WorkerServiceStatus statusEntry)+ /// <param name="status">The status to record.</param>+ private async Task WriteHeartbeatAsync(Status status){- if (globalServiceStatus.AreAllWorkersStopped())- {- await SetServiceStatus(statusEntry, Status.Stopped.ToString());- logger.LogInformation("All workers stopped.");- }- else- {- logger.LogInformation("Waiting for all workers to stop.");- }- }+ using var dbContext = createDbContext();+ var entry = await GetOrCreateStatusRecordAsync(dbContext);- /// <summary>- /// Gets the current status record of the service from database.- /// </summary>- /// <returns>New current status.</returns>- private async Task<WorkerServiceStatus> GetServiceStatus()- {- var entry = await GetOrCreateInitialStatusRecordAsync();-- if (!string.IsNullOrEmpty(entry.DesiredStatus) && entry.CurrentStatus != entry.DesiredStatus)+ var newStatus = status.ToString();+ if (entry.CurrentStatus != newStatus){- entry.CurrentStatus = entry.DesiredStatus.ToStatusEnum() switch- {- Status.Started => Status.Starting.ToString(),- Status.Stopped => Status.Stopping.ToString(),- _ => entry.CurrentStatus,- };+ logger.LogInformation("Service {ServiceName} status changed from {OldStatus} to {NewStatus}", globalServiceStatus.ServiceName, entry.CurrentStatus, newStatus);+ entry.CurrentStatus = newStatus;}- globalServiceStatus.Status = entry.CurrentStatus;- globalServiceStatus.CurrentStatus = entry.CurrentStatus;-entry.Heartbeat = DateTime.UtcNow;- await _dbContext.SaveChangesAsync();-- return entry;- }-- /// <summary>- /// Updates the status of the service.- /// </summary>- /// <param name="statusEntry">The WorkerServiceStatus entry to update.</param>- /// <param name="newStatus">The new status.</param>- /// <returns>New current status.</returns>- private async Task SetServiceStatus(WorkerServiceStatus statusEntry, string newStatus = "")- {- if (!string.IsNullOrEmpty(newStatus) && statusEntry.CurrentStatus != newStatus)- {- statusEntry.CurrentStatus = newStatus;- }-- var status = statusEntry.CurrentStatus;- globalServiceStatus.Status = status;- globalServiceStatus.CurrentStatus = status;-- statusEntry.Heartbeat = DateTime.UtcNow;- await _dbContext.SaveChangesAsync();+ await dbContext.SaveChangesAsync();}/// <summary>- /// Retrieves status record or creates an initial status record if it does not exist.- /// Also cleans up any duplicate records for the same service name.+ /// Retrieves the status record of the service or creates it if it does not exist.+ /// Also removes any duplicate records for the same service name./// </summary>- private async Task<WorkerServiceStatus> GetOrCreateInitialStatusRecordAsync()+ /// <param name="dbContext">The database context to use.</param>+ private async Task<WorkerServiceStatus> GetOrCreateStatusRecordAsync(IWorkerStatusDbContext dbContext){- var entries = _dbContext.WorkerServiceStatuses- .Where(x => x.ServiceName == globalServiceStatus.ServiceName)- .OrderBy(x => x.Id)- .ToList();+ var entries = dbContext.WorkerServiceStatuses.Where(x => x.ServiceName == globalServiceStatus.ServiceName).OrderBy(x => x.Id).ToList();if (entries.Count > 1){// Keep the first (oldest) record and remove duplicates.var duplicates = entries.Skip(1).ToList();- _dbContext.WorkerServiceStatuses.RemoveRange(duplicates);- await _dbContext.SaveChangesAsync();+ dbContext.WorkerServiceStatuses.RemoveRange(duplicates);+ await dbContext.SaveChangesAsync();logger.LogInformation("Removed {Count} duplicate status records for service {ServiceName}", duplicates.Count, globalServiceStatus.ServiceName);}@@ -217,14 +102,13 @@ public class StatusWorker(ILogger<StatusWorker> logger, Func<IWorkerStatusDbContvar entry = new WorkerServiceStatus{ServiceName = globalServiceStatus.ServiceName,- CurrentStatus = Status.Stopped.ToString(),- DesiredStatus = Status.Started.ToString(),+ CurrentStatus = Status.Starting.ToString(),Heartbeat = DateTime.UtcNow,};- _dbContext.WorkerServiceStatuses.Add(entry);- await _dbContext.SaveChangesAsync();+ dbContext.WorkerServiceStatuses.Add(entry);+ await dbContext.SaveChangesAsync();- logger.LogInformation("Created initial status record for service {ServiceName} with CurrentStatus={CurrentStatus}, DesiredStatus={DesiredStatus}", globalServiceStatus.ServiceName, entry.CurrentStatus, entry.DesiredStatus);+ logger.LogInformation("Created initial status record for service {ServiceName}", globalServiceStatus.ServiceName);return entry;}