Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add task runner job table and manual start button (#467)

Leendert de Borst0c5b2fb1da18
diff --git a/src/AliasVault.Admin/Main/Pages/Settings/Components/TaskRunnerHistory.razor b/src/AliasVault.Admin/Main/Pages/Settings/Components/TaskRunnerHistory.razor
new file mode 100644
index 000000000..a87726f7a
--- /dev/null
+++ b/src/AliasVault.Admin/Main/Pages/Settings/Components/TaskRunnerHistory.razor
@@ -0,0 +1,102 @@
+@using AliasVault.RazorComponents.Tables
+@using AliasVault.Shared.Models.Enums
+@inherits MainBase
+
+<div class="mb-4">
+ <Paginator CurrentPage="CurrentPage" PageSize="PageSize" TotalRecords="TotalRecords" OnPageChanged="HandlePageChanged" />
+
+ <SortableTable Columns="@_tableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">
+ @foreach (var job in JobList)
+ {
+ <SortableTableRow>
+ <SortableTableColumn IsPrimary="true">@job.Id</SortableTableColumn>
+ <SortableTableColumn>@job.RunDate.ToString("yyyy-MM-dd")</SortableTableColumn>
+ <SortableTableColumn>@job.StartTime.ToString("HH:mm")</SortableTableColumn>
+ <SortableTableColumn>@(job.EndTime?.ToString("HH:mm") ?? "-")</SortableTableColumn>
+ <SortableTableColumn>
+ @{
+ string bgColor = job.Status switch
+ {
+ TaskRunnerJobStatus.Pending => "bg-yellow-500",
+ TaskRunnerJobStatus.Running => "bg-blue-500",
+ TaskRunnerJobStatus.Finished => "bg-green-500",
+ TaskRunnerJobStatus.Error => "bg-red-500",
+ _ => "bg-gray-500"
+ };
+ }
+ <span class="px-2 py-1 rounded-full text-white @bgColor">
+ @job.Status
+ </span>
+ </SortableTableColumn>
+ <SortableTableColumn>@(job.IsOnDemand ? "Yes" : "No")</SortableTableColumn>
+ <SortableTableColumn Title="@job.ErrorMessage">
+ @if (!string.IsNullOrEmpty(job.ErrorMessage))
+ {
+ <span class="text-red-600 dark:text-red-400">@(job.ErrorMessage.Length > 50 ? job.ErrorMessage[..50] + "..." : job.ErrorMessage)</span>
+ }
+ </SortableTableColumn>
+ </SortableTableRow>
+ }
+ </SortableTable>
+</div>
+
+@code {
+ private readonly List<TableColumn> _tableColumns =
+ [
+ new TableColumn { Title = "ID", PropertyName = "Id" },
+ new TableColumn { Title = "Date", PropertyName = "RunDate" },
+ new TableColumn { Title = "Start", PropertyName = "StartTime" },
+ new TableColumn { Title = "End", PropertyName = "EndTime" },
+ new TableColumn { Title = "Status", PropertyName = "Status" },
+ new TableColumn { Title = "On-Demand", PropertyName = "IsOnDemand" },
+ new TableColumn { Title = "Error", PropertyName = "ErrorMessage" },
+ ];
+
+ private List<TaskRunnerJob> JobList { get; set; } = [];
+ private int CurrentPage { get; set; } = 1;
+ private int PageSize { get; set; } = 5;
+ private int TotalRecords { get; set; }
+ private string SortColumn { get; set; } = "Id";
+ private SortDirection SortDirection { get; set; } = SortDirection.Descending;
+
+ /// <summary>
+ /// Refreshes the data displayed in the table.
+ /// </summary>
+ public async Task RefreshData()
+ {
+ var dbContext = await DbContextFactory.CreateDbContextAsync();
+ var query = dbContext.TaskRunnerJobs.AsQueryable();
+
+ // Apply sorting
+ query = SortDirection == SortDirection.Ascending
+ ? query.OrderBy(x => EF.Property<object>(x, SortColumn))
+ : query.OrderByDescending(x => EF.Property<object>(x, SortColumn));
+
+ TotalRecords = await query.CountAsync();
+ JobList = await query
+ .Skip((CurrentPage - 1) * PageSize)
+ .Take(PageSize)
+ .ToListAsync();
+
+ StateHasChanged();
+ }
+
+ /// <inheritdoc/>
+ protected override async Task OnInitializedAsync()
+ {
+ await RefreshData();
+ }
+
+ private async Task HandlePageChanged(int newPage)
+ {
+ CurrentPage = newPage;
+ await RefreshData();
+ }
+
+ private async Task HandleSortChanged((string column, SortDirection direction) sort)
+ {
+ SortColumn = sort.column;
+ SortDirection = sort.direction;
+ await RefreshData();
+ }
+}
diff --git a/src/AliasVault.Admin/Main/Pages/Settings/Server.razor b/src/AliasVault.Admin/Main/Pages/Settings/Server.razor
index b24d18d81..d9ed32d2d 100644
--- a/src/AliasVault.Admin/Main/Pages/Settings/Server.razor
+++ b/src/AliasVault.Admin/Main/Pages/Settings/Server.razor
@@ -1,7 +1,10 @@
@page "/settings/server"
@inject ServerSettingsService SettingsService
+@inject ILogger<ServerSettingsService> Logger
+@using AliasVault.Shared.Models.Enums
@using AliasVault.Shared.Server.Models
@using AliasVault.Shared.Server.Services
+@using AliasVault.Admin.Main.Pages.Settings.Components
@inherits MainBase
<LayoutPageTitle>Server settings</LayoutPageTitle>
@@ -11,6 +14,7 @@
Title="Server settings"
Description="Configure AliasVault server settings.">
<CustomActions>
+ <RefreshButton OnClick="RefreshData" ButtonText="Refresh" />
<ConfirmButton OnClick="SaveSettings">Save changes</ConfirmButton>
</CustomActions>
</PageHeader>
@@ -40,7 +44,9 @@
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Set to 0 for unlimited emails</p>
</div>
</div>
+ </div>
+ <div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
<h3 class="mb-4 text-lg font-medium text-gray-900 dark:text-white">Maintenance Schedule</h3>
<div class="mb-4">
<label for="schedule" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Time (24h format)</label>
@@ -60,12 +66,23 @@
}
</div>
</div>
+
+ <div class="mb-4">
+ <h4 class="mb-2 text-md font-medium text-gray-900 dark:text-white">Manual Execution</h4>
+ <ConfirmButton OnClick="RunMaintenanceTasksNow">Run Maintenance Tasks Now</ConfirmButton>
+ </div>
+ </div>
+
+ <div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
+ <h3 class="mb-4 text-lg font-medium text-gray-900 dark:text-white">Maintenance History</h3>
+ <TaskRunnerHistory @ref="_taskRunnerHistoryComponent" />
</div>
</div>
@code {
- private ServerSettingsModel Settings { get; set; } = new();
+ private TaskRunnerHistory? _taskRunnerHistoryComponent;
+ private ServerSettingsModel Settings { get; set; } = new();
private readonly Dictionary<int, string> DaysOfWeek = new()
{
{ 1, "Monday" },
@@ -86,9 +103,13 @@
private void ToggleDay(int day)
{
if (Settings.TaskRunnerDays.Contains(day))
+ {
Settings.TaskRunnerDays.Remove(day);
+ }
else
+ {
Settings.TaskRunnerDays.Add(day);
+ }
}
private async Task SaveSettings()
@@ -96,4 +117,50 @@
await SettingsService.SaveSettingsAsync(Settings);
GlobalNotificationService.AddSuccessMessage("Settings saved successfully", true);
}
+
+ private async Task RunMaintenanceTasksNow()
+ {
+ try
+ {
+ var dbContext = await DbContextFactory.CreateDbContextAsync();
+ var job = new TaskRunnerJob
+ {
+ Name = nameof(TaskRunnerJobType.Maintenance),
+ RunDate = DateTime.Now.Date,
+ StartTime = TimeOnly.FromDateTime(DateTime.Now),
+ Status = TaskRunnerJobStatus.Pending,
+ IsOnDemand = true
+ };
+
+ dbContext.TaskRunnerJobs.Add(job);
+ await dbContext.SaveChangesAsync();
+
+ // Refresh the history component to show the new job
+ if (_taskRunnerHistoryComponent != null)
+ {
+ await _taskRunnerHistoryComponent.RefreshData();
+ }
+
+ Logger.LogWarning("Maintenance tasks manually queued.");
+ GlobalNotificationService.AddSuccessMessage("Maintenance tasks queued. They will be executed on the next polling cycle (default every minute). Check the logs for details.", true);
+ }
+ catch (Exception ex)
+ {
+ GlobalNotificationService.AddErrorMessage($"Failed to start maintenance tasks: {ex.Message}", true);
+ }
+ }
+
+ /// <summary>
+ /// Refreshes the data displayed on the page.
+ /// </summary>
+ private async Task RefreshData()
+ {
+ Settings = await SettingsService.GetAllSettingsAsync();
+
+ // Refresh the history component to show the new job
+ if (_taskRunnerHistoryComponent != null)
+ {
+ await _taskRunnerHistoryComponent.RefreshData();
+ }
+ }
}
diff --git a/src/Databases/AliasServerDb/AliasServerDbContext.cs b/src/Databases/AliasServerDb/AliasServerDbContext.cs
index 4a7c85de5..58ce789a4 100644
--- a/src/Databases/AliasServerDb/AliasServerDbContext.cs
+++ b/src/Databases/AliasServerDb/AliasServerDbContext.cs
@@ -133,6 +133,11 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon
/// </summary>
public DbSet<ServerSetting> ServerSettings { get; set; } = null!;
+ /// <summary>
+ /// Gets or sets the TaskRunnerJobs DbSet.
+ /// </summary>
+ public DbSet<TaskRunnerJob> TaskRunnerJobs { get; set; }
+
/// <summary>
/// The OnModelCreating method.
/// </summary>
diff --git a/src/Databases/AliasServerDb/Migrations/20241204121218_AddServerSettingsTable.cs b/src/Databases/AliasServerDb/Migrations/20241204121218_AddServerSettingsTable.cs
index 274846b3f..09b4cf09a 100644
--- a/src/Databases/AliasServerDb/Migrations/20241204121218_AddServerSettingsTable.cs
+++ b/src/Databases/AliasServerDb/Migrations/20241204121218_AddServerSettingsTable.cs
@@ -1,4 +1,5 @@
-using System;
+// <auto-generated />
+using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
diff --git a/src/Databases/AliasServerDb/Migrations/20241215131807_AddTaskRunnerJobTable.Designer.cs b/src/Databases/AliasServerDb/Migrations/20241215131807_AddTaskRunnerJobTable.Designer.cs
new file mode 100644
index 000000000..1926d91a1
--- /dev/null
+++ b/src/Databases/AliasServerDb/Migrations/20241215131807_AddTaskRunnerJobTable.Designer.cs
@@ -0,0 +1,881 @@
+// <auto-generated />
+using System;
+using AliasServerDb;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ [DbContext(typeof(AliasServerDbContext))]
+ [Migration("20241215131807_AddTaskRunnerJobTable")]
+ partial class AddTaskRunnerJobTable
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "9.0.0")
+ .HasAnnotation("Proxies:ChangeTracking", false)
+ .HasAnnotation("Proxies:CheckEquality", false)
+ .HasAnnotation("Proxies:LazyLoading", true);
+
+ modelBuilder.Entity("AliasServerDb.AdminRole", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AdminRoles");
+ });
+
+ 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("INTEGER");
+
+ b.Property<DateTime?>("LastPasswordChanged")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ 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("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AdminUsers");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultRole", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AliasVaultRoles");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("PasswordChangedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AliasVaultUsers");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("DeviceIdentifier")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("ExpireDate")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("IpAddress")
+ .HasMaxLength(45)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PreviousTokenValue")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AliasVaultUserRefreshTokens");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AuthLog", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("AdditionalInfo")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Browser")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Country")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("DeviceType")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property<int>("EventType")
+ .HasColumnType("nvarchar(50)");
+
+ b.Property<int?>("FailureReason")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("IpAddress")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsSuccess")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("IsSuspiciousActivity")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("OperatingSystem")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("RequestPath")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Timestamp")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserAgent")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Username")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ 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.Email", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Date")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("DateSystem")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("EncryptedSymmetricKey")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ 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")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PushNotificationSent")
+ .HasColumnType("INTEGER");
+
+ 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<Guid>("UserEncryptionKeyId")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Visible")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Date");
+
+ b.HasIndex("DateSystem");
+
+ b.HasIndex("PushNotificationSent");
+
+ b.HasIndex("ToLocal");
+
+ b.HasIndex("UserEncryptionKeyId");
+
+ b.HasIndex("Visible");
+
+ b.ToTable("Emails");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("Bytes")
+ .IsRequired()
+ .HasColumnType("BLOB");
+
+ b.Property<DateTime>("Date")
+ .HasColumnType("TEXT");
+
+ 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.Log", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Application")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Exception")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Level")
+ .IsRequired()
+ .HasMaxLength(128)
+ .HasColumnType("TEXT");
+
+ 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()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("TimeStamp")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Application");
+
+ b.HasIndex("TimeStamp");
+
+ b.ToTable("Logs", (string)null);
+ });
+
+ modelBuilder.Entity("AliasServerDb.ServerSetting", b =>
+ {
+ b.Property<string>("Key")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("ServerSettings");
+ });
+
+ modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<TimeOnly?>("EndTime")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ErrorMessage")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsOnDemand")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("RunDate")
+ .HasColumnType("TEXT");
+
+ b.Property<TimeOnly>("StartTime")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Status")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.ToTable("TaskRunnerJobs");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Address")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("AddressDomain")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("AddressLocal")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Address")
+ .IsUnique();
+
+ b.HasIndex("UserId");
+
+ b.ToTable("UserEmailClaims");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsPrimary")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("PublicKey")
+ .IsRequired()
+ .HasMaxLength(2000)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("UserEncryptionKeys");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Vault", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("CredentialsCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("EmailClaimsCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("EncryptionSettings")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("EncryptionType")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<int>("FileSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<long>("RevisionNumber")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Salt")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("VaultBlob")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Verifier")
+ .IsRequired()
+ .HasMaxLength(1000)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Version")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("Vaults");
+ });
+
+ modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CurrentStatus")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("DesiredStatus")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Heartbeat")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ServiceName")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("varchar");
+
+ b.HasKey("Id");
+
+ b.ToTable("WorkerServiceStatuses");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("FriendlyName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Xml")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("DataProtectionKeys");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("RoleId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("RoleClaims", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ 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.IdentityUserLogin<string>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.ToTable("UserLogins", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
+ {
+ b.Property<string>("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("RoleId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.ToTable("UserRoles", (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.AliasVaultUserRefreshToken", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.HasOne("AliasServerDb.UserEncryptionKey", "EncryptionKey")
+ .WithMany("Emails")
+ .HasForeignKey("UserEncryptionKeyId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("EncryptionKey");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
+ {
+ b.HasOne("AliasServerDb.Email", "Email")
+ .WithMany("Attachments")
+ .HasForeignKey("EmailId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Email");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("EmailClaims")
+ .HasForeignKey("UserId");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("EncryptionKeys")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Vault", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany("Vaults")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>
+ {
+ b.Navigation("EmailClaims");
+
+ b.Navigation("EncryptionKeys");
+
+ b.Navigation("Vaults");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.Navigation("Attachments");
+ });
+
+ modelBuilder.Entity("AliasServerDb.UserEncryptionKey", b =>
+ {
+ b.Navigation("Emails");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/Databases/AliasServerDb/Migrations/20241215131807_AddTaskRunnerJobTable.cs b/src/Databases/AliasServerDb/Migrations/20241215131807_AddTaskRunnerJobTable.cs
new file mode 100644
index 000000000..4c650df1c
--- /dev/null
+++ b/src/Databases/AliasServerDb/Migrations/20241215131807_AddTaskRunnerJobTable.cs
@@ -0,0 +1,42 @@
+// <auto-generated />
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddTaskRunnerJobTable : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "TaskRunnerJobs",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ Name = table.Column<string>(type: "TEXT", nullable: false),
+ RunDate = table.Column<DateTime>(type: "TEXT", nullable: false),
+ StartTime = table.Column<TimeOnly>(type: "TEXT", nullable: false),
+ EndTime = table.Column<TimeOnly>(type: "TEXT", nullable: true),
+ Status = table.Column<int>(type: "INTEGER", nullable: false),
+ ErrorMessage = table.Column<string>(type: "TEXT", nullable: true),
+ IsOnDemand = table.Column<bool>(type: "INTEGER", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_TaskRunnerJobs", x => x.Id);
+ });
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "TaskRunnerJobs");
+ }
+ }
+}
diff --git a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
index a12782aa1..2817f8a67 100644
--- a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
+++ b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
@@ -484,6 +484,39 @@ namespace AliasServerDb.Migrations
b.ToTable("ServerSettings");
});
+ modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<TimeOnly?>("EndTime")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ErrorMessage")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsOnDemand")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("RunDate")
+ .HasColumnType("TEXT");
+
+ b.Property<TimeOnly>("StartTime")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Status")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.ToTable("TaskRunnerJobs");
+ });
+
modelBuilder.Entity("AliasServerDb.UserEmailClaim", b =>
{
b.Property<Guid>("Id")
diff --git a/src/Databases/AliasServerDb/TaskRunnerJob.cs b/src/Databases/AliasServerDb/TaskRunnerJob.cs
new file mode 100644
index 000000000..6c2033de7
--- /dev/null
+++ b/src/Databases/AliasServerDb/TaskRunnerJob.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <copyright file="TaskRunnerJob.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasServerDb;
+
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using AliasVault.Shared.Models.Enums;
+
+/// <summary>
+/// Represents a task runner job entry in the AliasServerDb.
+/// </summary>
+public class TaskRunnerJob
+{
+ /// <summary>
+ /// Gets or sets the ID of the task runner job.
+ /// </summary>
+ [Key]
+ public int Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the name of the task runner job.
+ /// </summary>
+ [Required]
+ [Column(TypeName = "nvarchar(50)")]
+ public string Name { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the date the job was run.
+ /// </summary>
+ public DateTime RunDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the start time of the job.
+ /// </summary>
+ public TimeOnly StartTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the end time of the job.
+ /// </summary>
+ public TimeOnly? EndTime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the status of the job.
+ /// </summary>
+ public TaskRunnerJobStatus Status { get; set; }
+
+ /// <summary>
+ /// Gets or sets the error message of the job.
+ /// </summary>
+ public string? ErrorMessage { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this is an on-demand run.
+ /// </summary>
+ public bool IsOnDemand { get; set; }
+}
diff --git a/src/Services/AliasVault.TaskRunner/Tasks/LogCleanupTask.cs b/src/Services/AliasVault.TaskRunner/Tasks/LogCleanupTask.cs
index 777f63f6f..c22602e3e 100644
--- a/src/Services/AliasVault.TaskRunner/Tasks/LogCleanupTask.cs
+++ b/src/Services/AliasVault.TaskRunner/Tasks/LogCleanupTask.cs
@@ -52,6 +52,13 @@ public class LogCleanupTask : IMaintenanceTask
.Where(x => x.TimeStamp < cutoffDate)
.ExecuteDeleteAsync(cancellationToken);
_logger.LogWarning("Deleted {Count} general log entries older than {Days} days", deletedCount, settings.GeneralLogRetentionDays);
+
+ // Delete old task runner jobs
+ var jobCutoffDate = DateTime.UtcNow.AddDays(-settings.GeneralLogRetentionDays);
+ var deletedJobCount = await dbContext.TaskRunnerJobs
+ .Where(x => x.RunDate < jobCutoffDate)
+ .ExecuteDeleteAsync(cancellationToken);
+ _logger.LogWarning("Deleted {Count} task runner job entries older than {Days} days", deletedJobCount, settings.GeneralLogRetentionDays);
}
if (settings.AuthLogRetentionDays > 0)
diff --git a/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs b/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs
index 438bb7463..dde5d7fd9 100644
--- a/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs
+++ b/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs
@@ -7,8 +7,11 @@
namespace AliasVault.TaskRunner.Workers;
+using AliasServerDb;
+using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Server.Services;
using AliasVault.TaskRunner.Tasks;
+using Microsoft.EntityFrameworkCore;
/// <summary>
/// A worker for the TaskRunner.
@@ -16,54 +19,115 @@ using AliasVault.TaskRunner.Tasks;
/// <param name="logger">ILogger instance.</param>
/// <param name="tasks">List of maintenance tasks.</param>
/// <param name="settingsService">Server settings service.</param>
-public class TaskRunnerWorker(ILogger<TaskRunnerWorker> logger, IEnumerable<IMaintenanceTask> tasks, ServerSettingsService settingsService) : BackgroundService
+/// <param name="dbContextFactory">Database context factory.</param>
+public class TaskRunnerWorker(
+ ILogger<TaskRunnerWorker> logger,
+ IEnumerable<IMaintenanceTask> tasks,
+ ServerSettingsService settingsService,
+ IDbContextFactory<AliasServerDbContext> dbContextFactory) : BackgroundService
{
- private DateTime _nextRun = DateTime.MinValue;
-
- /// <inheritdoc />
+ /// <inheritdoc/>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogWarning("TaskRunnerWorker started at: {Time}", DateTimeOffset.Now);
while (!stoppingToken.IsCancellationRequested)
{
+ await using var dbContext = await dbContextFactory.CreateDbContextAsync(stoppingToken);
var settings = await settingsService.GetAllSettingsAsync();
var now = DateTime.Now;
+ var today = now.Date;
- // Calculate if we should run now or wait
- var scheduledTime = settings.MaintenanceTime;
- var currentTime = TimeOnly.FromDateTime(now);
- var shouldRunToday = settings.TaskRunnerDays.Contains((int)now.DayOfWeek);
- var hasPassedScheduledTime = currentTime >= scheduledTime;
+ // Check for on-demand run request
+ var onDemandJob = await dbContext.TaskRunnerJobs
+ .Where(j => j.IsOnDemand && j.Status == TaskRunnerJobStatus.Pending)
+ .OrderByDescending(j => j.StartTime)
+ .FirstOrDefaultAsync(stoppingToken);
- // Run if:
- // 1. We haven't run yet today (nextRun is from previous day)
- // 2. It's a scheduled day
- // 3. The scheduled time has passed
- if (shouldRunToday && hasPassedScheduledTime && now.Date >= _nextRun.Date)
+ if (onDemandJob != null)
+ {
+ await ExecuteMaintenanceTasks(onDemandJob, dbContext, stoppingToken);
+ }
+ else
{
- logger.LogWarning("Starting maintenance tasks at {Time}", now);
+ // Regular scheduled run logic
+ var scheduledTime = settings.MaintenanceTime;
+ var currentTime = TimeOnly.FromDateTime(now);
+ var shouldRunToday = settings.TaskRunnerDays.Contains((int)now.DayOfWeek + 1);
+ var hasPassedScheduledTime = currentTime >= scheduledTime;
- foreach (var task in tasks)
+ if (shouldRunToday && hasPassedScheduledTime)
{
- try
- {
- await task.ExecuteAsync(stoppingToken);
- }
- catch (Exception ex)
+ var existingJob = await dbContext.TaskRunnerJobs
+ .Where(j => j.Name == nameof(TaskRunnerJobType.Maintenance) && !j.IsOnDemand && j.RunDate.Date == today)
+ .OrderByDescending(j => j.StartTime)
+ .FirstOrDefaultAsync(stoppingToken);
+
+ if (existingJob == null)
{
- logger.LogError(ex, "Error executing task {TaskName}", task.Name);
+ var job = new TaskRunnerJob
+ {
+ Name = nameof(TaskRunnerJobType.Maintenance),
+ RunDate = today,
+ StartTime = TimeOnly.FromDateTime(now),
+ Status = TaskRunnerJobStatus.Running,
+ IsOnDemand = false,
+ };
+
+ dbContext.TaskRunnerJobs.Add(job);
+ await dbContext.SaveChangesAsync(stoppingToken);
+
+ await ExecuteMaintenanceTasks(job, dbContext, stoppingToken);
}
}
-
- // Set next run to tomorrow at the scheduled time
- _nextRun = now.Date.AddDays(1);
- logger.LogInformation("Tasks completed. Next run scheduled for date: {NextRun}", _nextRun);
}
- // Calculate delay until next check
- // Check every minute for schedule changes, but not more often than that
+ // Check every minute for schedule changes or on-demand requests
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
+
+ /// <summary>
+ /// Executes the maintenance tasks.
+ /// </summary>
+ /// <param name="job">The job to execute.</param>
+ /// <param name="dbContext">The database context.</param>
+ /// <param name="stoppingToken">The cancellation token.</param>
+ private async Task ExecuteMaintenanceTasks(TaskRunnerJob job, AliasServerDbContext dbContext, CancellationToken stoppingToken)
+ {
+ logger.LogWarning("Starting maintenance tasks at {Time} (On-demand: {IsOnDemand})", DateTime.Now, job.IsOnDemand);
+
+ try
+ {
+ foreach (var task in tasks)
+ {
+ try
+ {
+ job.Status = TaskRunnerJobStatus.Running;
+ await dbContext.SaveChangesAsync(stoppingToken);
+ await task.ExecuteAsync(stoppingToken);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error executing task {TaskName}", task.Name);
+ job.ErrorMessage = $"Task {task.Name} failed: {ex.Message}";
+ job.Status = TaskRunnerJobStatus.Error;
+ await dbContext.SaveChangesAsync(stoppingToken);
+ break;
+ }
+ }
+
+ if (job.Status != TaskRunnerJobStatus.Error)
+ {
+ job.Status = TaskRunnerJobStatus.Finished;
+ }
+ }
+ finally
+ {
+ job.EndTime = TimeOnly.FromDateTime(DateTime.Now);
+ await dbContext.SaveChangesAsync(stoppingToken);
+ }
+
+ logger.LogInformation("Tasks completed with status: {Status}", job.Status);
+ }
}
diff --git a/src/Shared/AliasVault.Shared/Models/Enums/TaskRunnerJobStatus.cs b/src/Shared/AliasVault.Shared/Models/Enums/TaskRunnerJobStatus.cs
new file mode 100644
index 000000000..6c9a56031
--- /dev/null
+++ b/src/Shared/AliasVault.Shared/Models/Enums/TaskRunnerJobStatus.cs
@@ -0,0 +1,34 @@
+//-----------------------------------------------------------------------
+// <copyright file="TaskRunnerJobStatus.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.Enums;
+
+/// <summary>
+/// The status of a task runner job.
+/// </summary>
+public enum TaskRunnerJobStatus
+{
+ /// <summary>
+ /// The job is pending.
+ /// </summary>
+ Pending = 0,
+
+ /// <summary>
+ /// The job is running.
+ /// </summary>
+ Running = 1,
+
+ /// <summary>
+ /// The job has finished.
+ /// </summary>
+ Finished = 2,
+
+ /// <summary>
+ /// The job has failed.
+ /// </summary>
+ Error = 9,
+}
diff --git a/src/Shared/AliasVault.Shared/Models/Enums/TaskRunnerJobType.cs b/src/Shared/AliasVault.Shared/Models/Enums/TaskRunnerJobType.cs
new file mode 100644
index 000000000..15c965c16
--- /dev/null
+++ b/src/Shared/AliasVault.Shared/Models/Enums/TaskRunnerJobType.cs
@@ -0,0 +1,19 @@
+//-----------------------------------------------------------------------
+// <copyright file="TaskRunnerJobType.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.Enums;
+
+/// <summary>
+/// The type of a task runner job.
+/// </summary>
+public enum TaskRunnerJobType
+{
+ /// <summary>
+ /// The job is pending.
+ /// </summary>
+ Maintenance,
+}
diff --git a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
index 11316c5bb..baec7b378 100644
--- a/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
+++ b/src/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
@@ -148,11 +148,7 @@ public class TaskRunnerTests
await SeedData.SeedDatabase(_testHostBuilder.GetDbContext());
// Get current day of week (1-7, Monday = 1, Sunday = 7)
- var currentDay = (int)DateTime.Now.DayOfWeek;
- if (currentDay == 0)
- {
- currentDay = 7; // Convert Sunday from 0 to 7
- }
+ var currentDay = (int)DateTime.Now.DayOfWeek + 1;
// Update maintenance settings in database to exclude current day
var dbContext = _testHostBuilder.GetDbContext();