Skip to content

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

Add task runner implementation (#221)

Leendert de Borstd147639a8399
diff --git a/src/Services/AliasVault.TaskRunner/AliasVault.TaskRunner.csproj b/src/Services/AliasVault.TaskRunner/AliasVault.TaskRunner.csproj
index a17c2c2ac..5e3515ada 100644
--- a/src/Services/AliasVault.TaskRunner/AliasVault.TaskRunner.csproj
+++ b/src/Services/AliasVault.TaskRunner/AliasVault.TaskRunner.csproj
@@ -35,6 +35,7 @@
<ItemGroup>
<ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />
+ <ProjectReference Include="..\..\Shared\AliasVault.Shared.Server\AliasVault.Shared.Server.csproj" />
<ProjectReference Include="..\..\Utilities\AliasVault.Logging\AliasVault.Logging.csproj" />
<ProjectReference Include="..\..\Utilities\Cryptography\AliasVault.Cryptography.Server\AliasVault.Cryptography.Server.csproj" />
</ItemGroup>
diff --git a/src/Services/AliasVault.TaskRunner/Program.cs b/src/Services/AliasVault.TaskRunner/Program.cs
index b9c736f3c..b04d838b4 100644
--- a/src/Services/AliasVault.TaskRunner/Program.cs
+++ b/src/Services/AliasVault.TaskRunner/Program.cs
@@ -9,7 +9,9 @@ using System.Reflection;
using AliasServerDb;
using AliasServerDb.Configuration;
using AliasVault.Logging;
+using AliasVault.Shared.Server.Services;
using AliasVault.TaskRunner;
+using AliasVault.TaskRunner.Tasks;
using AliasVault.TaskRunner.Workers;
using AliasVault.WorkerStatus.ServiceExtensions;
using Microsoft.EntityFrameworkCore;
@@ -35,6 +37,11 @@ builder.Services.AddAliasVaultSqliteConfiguration();
// -----------------------------------------------------------------------
// Register hosted services via Status library wrapper in order to monitor and control (start/stop) them via the database.
// -----------------------------------------------------------------------
+builder.Services.AddSingleton<ServerSettingsService>();
+
+// Define the tasks that will be executed by the TaskRunner.
+builder.Services.AddTransient<IMaintenanceTask, LogCleanupTask>();
+
builder.Services.AddStatusHostedService<TaskRunnerWorker, AliasServerDbContext>(Assembly.GetExecutingAssembly().GetName().Name!);
var host = builder.Build();
diff --git a/src/Services/AliasVault.TaskRunner/Tasks/IMaintenanceTask.cs b/src/Services/AliasVault.TaskRunner/Tasks/IMaintenanceTask.cs
new file mode 100644
index 000000000..9fc9e8a85
--- /dev/null
+++ b/src/Services/AliasVault.TaskRunner/Tasks/IMaintenanceTask.cs
@@ -0,0 +1,26 @@
+//-----------------------------------------------------------------------
+// <copyright file="IMaintenanceTask.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.TaskRunner.Tasks;
+
+/// <summary>
+/// Interface for maintenance tasks that can be executed by the TaskRunner.
+/// </summary>
+public interface IMaintenanceTask
+{
+ /// <summary>
+ /// Gets the name of the task.
+ /// </summary>
+ string Name { get; }
+
+ /// <summary>
+ /// Executes the maintenance task.
+ /// </summary>
+ /// <param name="cancellationToken">Cancellation token.</param>
+ /// <returns>A task representing the asynchronous operation.</returns>
+ Task ExecuteAsync(CancellationToken cancellationToken);
+}
diff --git a/src/Services/AliasVault.TaskRunner/Tasks/LogCleanupTask.cs b/src/Services/AliasVault.TaskRunner/Tasks/LogCleanupTask.cs
new file mode 100644
index 000000000..777f63f6f
--- /dev/null
+++ b/src/Services/AliasVault.TaskRunner/Tasks/LogCleanupTask.cs
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------
+// <copyright file="LogCleanupTask.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.TaskRunner.Tasks;
+
+using AliasServerDb;
+using AliasVault.Shared.Server.Services;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// A maintenance task that deletes old log entries.
+/// </summary>
+public class LogCleanupTask : IMaintenanceTask
+{
+ private readonly ILogger<LogCleanupTask> _logger;
+ private readonly IDbContextFactory<AliasServerDbContext> _dbContextFactory;
+ private readonly ServerSettingsService _settingsService;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="LogCleanupTask"/> class.
+ /// </summary>
+ /// <param name="logger">The logger.</param>
+ /// <param name="dbContextFactory">The database context factory.</param>
+ /// <param name="settingsService">The settings service.</param>
+ public LogCleanupTask(
+ ILogger<LogCleanupTask> logger,
+ IDbContextFactory<AliasServerDbContext> dbContextFactory,
+ ServerSettingsService settingsService)
+ {
+ _logger = logger;
+ _dbContextFactory = dbContextFactory;
+ _settingsService = settingsService;
+ }
+
+ /// <inheritdoc />
+ public string Name => "Log Cleanup";
+
+ /// <inheritdoc />
+ public async Task ExecuteAsync(CancellationToken cancellationToken)
+ {
+ var settings = await _settingsService.GetAllSettingsAsync();
+ await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
+
+ if (settings.GeneralLogRetentionDays > 0)
+ {
+ var cutoffDate = DateTime.UtcNow.AddDays(-settings.GeneralLogRetentionDays);
+ var deletedCount = await dbContext.Logs
+ .Where(x => x.TimeStamp < cutoffDate)
+ .ExecuteDeleteAsync(cancellationToken);
+ _logger.LogWarning("Deleted {Count} general log entries older than {Days} days", deletedCount, settings.GeneralLogRetentionDays);
+ }
+
+ if (settings.AuthLogRetentionDays > 0)
+ {
+ var cutoffDate = DateTime.UtcNow.AddDays(-settings.AuthLogRetentionDays);
+ var deletedCount = await dbContext.AuthLogs
+ .Where(x => x.Timestamp < cutoffDate)
+ .ExecuteDeleteAsync(cancellationToken);
+ _logger.LogWarning("Deleted {Count} auth log entries older than {Days} days", deletedCount, settings.AuthLogRetentionDays);
+ }
+ }
+}
diff --git a/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs b/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs
index 1437d3584..438bb7463 100644
--- a/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs
+++ b/src/Services/AliasVault.TaskRunner/Workers/TaskRunnerWorker.cs
@@ -7,16 +7,63 @@
namespace AliasVault.TaskRunner.Workers;
+using AliasVault.Shared.Server.Services;
+using AliasVault.TaskRunner.Tasks;
+
/// <summary>
/// A worker for the TaskRunner.
/// </summary>
/// <param name="logger">ILogger instance.</param>
-public class TaskRunnerWorker(ILogger<TaskRunnerWorker> logger) : BackgroundService
+/// <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
{
+ private DateTime _nextRun = DateTime.MinValue;
+
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
- logger.LogWarning("AliasVault.TaskRunnerWorker started at: {Time}", DateTimeOffset.Now);
- await Task.Delay(1000);
+ logger.LogWarning("TaskRunnerWorker started at: {Time}", DateTimeOffset.Now);
+
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ var settings = await settingsService.GetAllSettingsAsync();
+ var now = DateTime.Now;
+
+ // 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;
+
+ // 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)
+ {
+ logger.LogWarning("Starting maintenance tasks at {Time}", now);
+
+ foreach (var task in tasks)
+ {
+ try
+ {
+ await task.ExecuteAsync(stoppingToken);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error executing task {TaskName}", task.Name);
+ }
+ }
+
+ // 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
+ await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
+ }
}
}