Skip to content

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

Refactor StatusWorker library (#113)

Leendert de Borst1e9dd71a7a9a
diff --git a/src/Services/AliasVault.SmtpService/Program.cs b/src/Services/AliasVault.SmtpService/Program.cs
index c6b5c5eed..81fccb8ce 100644
--- a/src/Services/AliasVault.SmtpService/Program.cs
+++ b/src/Services/AliasVault.SmtpService/Program.cs
@@ -17,8 +17,8 @@ using SmtpServer;
using SmtpServer.Storage;
using AliasVault.Logging;
using AliasVault.SmtpService.Workers;
-using AliasVault.WorkerStatus;
using AliasVault.WorkerStatus.Database;
+using AliasVault.WorkerStatus.ServiceExtensions;
var builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
@@ -123,30 +123,12 @@ builder.Services.AddSingleton(
);
// -----------------------------------------------------------------------
-// Worker status service registration.
+// Register hosted services via Status library wrapper in order to monitor and control (start/stop) them via the database.
// -----------------------------------------------------------------------
-var globalServiceStatus = new GlobalServiceStatus();
-builder.Services.AddSingleton(globalServiceStatus);
-
-builder.Services.AddSingleton<Func<IWorkerStatusDbContext>>(sp =>
-{
- var factory = sp.GetRequiredService<IDbContextFactory<AliasServerDbContext>>();
- return () => factory.CreateDbContext();
-});
-
-builder.Services.AddSingleton(sp => new WorkerStatusConfiguration
-{
- ServiceName = Assembly.GetExecutingAssembly().GetName().Name!,
- GlobalServiceStatus = sp.GetRequiredService<GlobalServiceStatus>(),
-});
-
-builder.Services.AddHostedService<StatusWorker>();
-
-// Register the names of the various worker services here so their status can be monitored.
-globalServiceStatus.RegisterWorker(nameof(SmtpServerWorker));
+builder.Services.AddStatusHostedService<SmtpServerWorker, AliasServerDbContext>(Assembly.GetExecutingAssembly().GetName().Name!);
// -----------------------------------------------------------------------
-
-builder.Services.AddHostedService<SmtpServerWorker>();
+// vs:
+// builder.Services.AddHostedService<SmtpServerWorker>();
var host = builder.Build();
diff --git a/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs b/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs
index 4af73a786..bcb0286bd 100644
--- a/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs
+++ b/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs
@@ -7,101 +7,14 @@
namespace AliasVault.SmtpService.Workers;
-using AliasVault.WorkerStatus;
-
-public class SmtpServerWorker(ILogger<SmtpServerWorker> logger, GlobalServiceStatus globalServiceStatus, SmtpServer.SmtpServer smtpServer) : BackgroundService
+public class SmtpServerWorker(ILogger<SmtpServerWorker> logger, SmtpServer.SmtpServer smtpServer) : BackgroundService
{
- private Task? _workerTask;
- private readonly object _taskLock = new();
-
/// <inheritdoc />
- protected override async Task ExecuteAsync(CancellationToken serviceCancellationToken)
- {
- logger.LogInformation("AliasVault.SmtpService.SmtpServerWorker ExecuteAsync called.");
-
- while (!serviceCancellationToken.IsCancellationRequested)
- {
- var workerCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(serviceCancellationToken);
-
- await ExecuteInnerAsync(workerCancellationTokenSource);
- _workerTask = null;
-
- await Task.Delay(1000, serviceCancellationToken);
- }
- }
-
- private async Task ExecuteInnerAsync(CancellationTokenSource workerCancellationTokenSource)
+ protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
- // Shutdown the SMTP server if it's running.
- //smtpServer.Shutdown();
- _workerTask = null;
-
- while (!workerCancellationTokenSource.IsCancellationRequested)
- {
- if (globalServiceStatus.CurrentStatus == "Started" || globalServiceStatus.CurrentStatus == "Starting")
- {
- // Start the worker in the background with the cancellation token so we can stop it later.
- lock (_taskLock)
- {
- if (_workerTask == null)
- {
- // Create a new cancellation token source for worker.
- _workerTask = Task.Run(() => WorkerLogic(workerCancellationTokenSource.Token),
- workerCancellationTokenSource.Token);
- }
- }
- }
- else if (globalServiceStatus.CurrentStatus == "Stopping")
- {
- // Request the worker to stop.
- await workerCancellationTokenSource.CancelAsync();
- }
- else if (globalServiceStatus.CurrentStatus == "Stopped")
- {
- // Reset the worker task if the service is stopped so it can be started again later.
- _workerTask = null;
- break;
- }
- }
- }
-
- /// <summary>
- /// Actual worker logic.
- /// </summary>
- /// <param name="stoppingToken"></param>
- private async Task WorkerLogic(CancellationToken stoppingToken)
- {
- try
- {
- logger.LogWarning("AliasVault.SmtpService starting at: {Time}", DateTimeOffset.Now);
-
- // Set worker status to true for acknowledgement.
- globalServiceStatus.SetWorkerStatus(nameof(SmtpServerWorker), true);
-
- // Start the SMTP server
- await smtpServer.StartAsync(stoppingToken);
-
- // Wait for the cancellation token to be triggered
- await Task.Delay(Timeout.Infinite, stoppingToken);
- }
- catch (OperationCanceledException ex)
- {
- // This exception is thrown when the stoppingToken is canceled
- // It's expected behavior, so we can just log it
- logger.LogWarning(ex, "AliasVault.SmtpService is stopping due to a cancellation request.");
- }
- catch (Exception ex)
- {
- // Log any unexpected exceptions
- logger.LogError(ex, "An error occurred in AliasVault.SmtpService");
- }
- finally
- {
- // Log that the service is stopping, whether it's due to cancellation or an error
- logger.LogWarning("AliasVault.SmtpService stopped at: {Time}", DateTimeOffset.Now);
+ logger.LogWarning("AliasVault.SmtpService started at: {Time}", DateTimeOffset.Now);
- // Set worker status to false for acknowledgement.
- globalServiceStatus.SetWorkerStatus(nameof(SmtpServerWorker), false);
- }
+ // Start the SMTP server
+ await smtpServer.StartAsync(cancellationToken);
}
}
diff --git a/src/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.cs b/src/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.cs
index 0c0a1fe2f..8e4cea40c 100644
--- a/src/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.cs
+++ b/src/Utilities/AliasVault.WorkerStatus/GlobalServiceStatus.cs
@@ -16,6 +16,15 @@ public class GlobalServiceStatus
{
private readonly ConcurrentDictionary<string, bool> _workerStatuses = new();
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GlobalServiceStatus"/> class.
+ /// </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>
@@ -26,6 +35,11 @@ public class GlobalServiceStatus
/// </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; } = null!;
+
/// <summary>
/// Register a worker with the service.
/// </summary>
diff --git a/src/Utilities/AliasVault.WorkerStatus/ServiceExtensions/ServiceCollectionExtensions.cs b/src/Utilities/AliasVault.WorkerStatus/ServiceExtensions/ServiceCollectionExtensions.cs
new file mode 100644
index 000000000..85515362f
--- /dev/null
+++ b/src/Utilities/AliasVault.WorkerStatus/ServiceExtensions/ServiceCollectionExtensions.cs
@@ -0,0 +1,57 @@
+//-----------------------------------------------------------------------
+// <copyright file="ServiceCollectionExtensions.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>
+//-----------------------------------------------------------------------
+
+using AliasVault.WorkerStatus.Database;
+using Microsoft.EntityFrameworkCore;
+
+namespace AliasVault.WorkerStatus.ServiceExtensions;
+
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Hosting;
+
+/// <summary>
+/// ServiceCollectionExtensions class.
+/// </summary>
+public static class ServiceCollectionExtensions
+{
+ /// <summary>
+ /// Add a HostedService that is monitored by the StatusWorker.
+ /// </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>
+ /// <returns>IServiceCollection instance.</returns>
+ public static IServiceCollection AddStatusHostedService<TWorker, TContext>(this IServiceCollection services, string serviceName)
+ where TWorker : class, IHostedService
+ where TContext : DbContext, IWorkerStatusDbContext
+ {
+ services.TryAddSingleton<TWorker>(); // Register the inner service
+ services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, StatusHostedService<TWorker>>()); // Register the status hosted service
+
+ // Only add these required helper services if they are not already registered.
+ services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, StatusWorker>());
+ services.TryAddSingleton(new GlobalServiceStatus(serviceName));
+
+ // Register the DbContext factory
+ services.TryAddSingleton<Func<IWorkerStatusDbContext>>(sp =>
+ {
+ var factory = sp.GetRequiredService<IDbContextFactory<TContext>>();
+ return () => factory.CreateDbContext();
+ });
+
+ // Set HostOptions to ignore background service exceptions as we are handling them in the StatusWorker.
+ services.Configure<HostOptions>(options =>
+ {
+ options.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore;
+ });
+
+ return services;
+ }
+}
diff --git a/src/Utilities/AliasVault.WorkerStatus/ServiceExtensions/StatusHostedService.cs b/src/Utilities/AliasVault.WorkerStatus/ServiceExtensions/StatusHostedService.cs
new file mode 100644
index 000000000..d6639672a
--- /dev/null
+++ b/src/Utilities/AliasVault.WorkerStatus/ServiceExtensions/StatusHostedService.cs
@@ -0,0 +1,157 @@
+//-----------------------------------------------------------------------
+// <copyright file="StatusHostedService.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.WorkerStatus.ServiceExtensions;
+
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+/// <summary>
+/// StatusHostedService class.
+/// </summary>
+/// <typeparam name="T">The HostedService to add.</typeparam>
+public class StatusHostedService<T>(ILogger<StatusHostedService<T>> logger, GlobalServiceStatus globalServiceStatus, T innerService) : BackgroundService
+ where 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"/>.
+ /// </summary>
+ private const int _restartMinDelayInMs = 1000;
+
+ /// <summary>
+ /// Maximum delay before restarting the worker.
+ /// </summary>
+ private const int _restartMaxDelayInMs = 300000;
+
+ /// <summary>
+ /// Current delay before restarting the worker.
+ /// </summary>
+ private int _restartDelayInMs = _restartMinDelayInMs;
+
+ private readonly object _taskLock = new();
+ private Task? _workerTask;
+
+ /// <summary>
+ /// Default entry point called by the host.
+ /// </summary>
+ /// <param name="serviceCancellationToken">Cancellation token.</param>
+ /// <returns>Task.</returns>
+ protected override async Task ExecuteAsync(CancellationToken serviceCancellationToken)
+ {
+ logger.LogInformation("StatusHostedService<{ServiceType}> ExecuteAsync called.", typeof(T).Name);
+
+ // Register the service with the global service status so the StatusWorker will monitor it.
+ globalServiceStatus.RegisterWorker(typeof(T).Name);
+
+ while (!serviceCancellationToken.IsCancellationRequested)
+ {
+ // 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.
+ var workerCancellationTokenSource =
+ CancellationTokenSource.CreateLinkedTokenSource(serviceCancellationToken);
+
+ // Start the inner while loop with the second cancellationToken.
+ await ExecuteInnerAsync(workerCancellationTokenSource);
+
+ if (!serviceCancellationToken.IsCancellationRequested)
+ {
+ // If the worker was not stopped, wait for a second before attempting to restart it.
+ await Task.Delay(1000, serviceCancellationToken);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Start the inner while loop which adds a second cancellationToken that is controlled by the StatusWorker.
+ /// </summary>
+ /// <param name="workerCancellationTokenSource">Cancellation token.</param>
+ private async Task ExecuteInnerAsync(CancellationTokenSource workerCancellationTokenSource)
+ {
+ _workerTask = null;
+
+ while (!workerCancellationTokenSource.IsCancellationRequested)
+ {
+ if (globalServiceStatus.CurrentStatus == "Started" || globalServiceStatus.CurrentStatus == "Starting")
+ {
+ lock (_taskLock)
+ {
+ if (_workerTask == null)
+ {
+ globalServiceStatus.SetWorkerStatus(typeof(T).Name, true);
+ _workerTask = Task.Run(() => WorkerLogic(workerCancellationTokenSource.Token), workerCancellationTokenSource.Token);
+ }
+ }
+ }
+ else if (globalServiceStatus.CurrentStatus == "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 == "Stopped")
+ {
+ _workerTask = null;
+ break;
+ }
+ }
+ }
+
+ /// <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);
+
+ await innerService.StartAsync(cancellationToken);
+
+ await Task.Delay(Timeout.Infinite, 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);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "An error occurred in StatusHostedService<{ServiceType}>", typeof(T).Name);
+ }
+ finally
+ {
+ logger.LogWarning("StatusHostedService<{ServiceType}> stopped at: {Time}", typeof(T).Name, DateTimeOffset.Now);
+ globalServiceStatus.SetWorkerStatus(typeof(T).Name, false);
+ }
+
+ // If a fault occurred in the innerService but it was not canceled,
+ // wait for a second before attempting to auto-restart the worker.
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ try
+ {
+ await Task.Delay(_restartDelayInMs, cancellationToken);
+ break; // Exit the loop if delay is successful
+ }
+ catch (TaskCanceledException)
+ {
+ // If the delay is canceled, exit the loop
+ break;
+ }
+ }
+
+ // Exponential backoff with a maximum delay
+ _restartDelayInMs = Math.Min(_restartDelayInMs * 2, _restartMaxDelayInMs);
+ }
+ }
+}
diff --git a/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs b/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs
index 5f9ed2094..c7d8e796b 100644
--- a/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs
+++ b/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs
@@ -14,7 +14,7 @@ using Microsoft.Extensions.Logging;
/// <summary>
/// StatusWorker class for monitoring and controlling the status of the worker services.
/// </summary>
-public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguration config, Func<IWorkerStatusDbContext> createDbContext) : BackgroundService
+public class StatusWorker(ILogger<StatusWorker> logger, Func<IWorkerStatusDbContext> createDbContext, GlobalServiceStatus globalServiceStatus) : BackgroundService
{
private IWorkerStatusDbContext _dbContext = null!;
@@ -34,6 +34,15 @@ public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguratio
var statusEntry = await GetServiceStatus();
switch (statusEntry.CurrentStatus)
{
+ case "Started":
+ // Ensure that all workers are running, if not, revert to "Starting" CurrentStatus.
+ if (!globalServiceStatus.AreAllWorkersRunning())
+ {
+ await SetServiceStatus(statusEntry, "Starting");
+ logger.LogInformation("Not all workers are running (yet). Reverting to Starting.");
+ }
+
+ break;
case "Starting":
await WaitForAllWorkersToStart(stoppingToken);
await SetServiceStatus(statusEntry, "Started");
@@ -81,8 +90,8 @@ public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguratio
};
}
- config.GlobalServiceStatus.Status = entry.CurrentStatus;
- config.GlobalServiceStatus.CurrentStatus = entry.CurrentStatus;
+ globalServiceStatus.Status = entry.CurrentStatus;
+ globalServiceStatus.CurrentStatus = entry.CurrentStatus;
entry.Heartbeat = DateTime.Now;
await _dbContext.SaveChangesAsync();
@@ -104,8 +113,8 @@ public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguratio
}
var status = statusEntry.CurrentStatus;
- config.GlobalServiceStatus.Status = status;
- config.GlobalServiceStatus.CurrentStatus = status;
+ globalServiceStatus.Status = status;
+ globalServiceStatus.CurrentStatus = status;
statusEntry.Heartbeat = DateTime.Now;
await _dbContext.SaveChangesAsync();
@@ -117,7 +126,7 @@ public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguratio
/// <param name="stoppingToken">CancellationToken.</param>
private async Task WaitForAllWorkersToStart(CancellationToken stoppingToken)
{
- while (!config.GlobalServiceStatus.AreAllWorkersRunning())
+ while (!globalServiceStatus.AreAllWorkersRunning())
{
logger.LogInformation("Waiting for all workers to start...");
await Task.Delay(1000, stoppingToken);
@@ -130,7 +139,7 @@ public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguratio
/// <param name="stoppingToken">CancellationToken.</param>
private async Task WaitForAllWorkersToStop(CancellationToken stoppingToken)
{
- while (!config.GlobalServiceStatus.AreAllWorkersStopped())
+ while (!globalServiceStatus.AreAllWorkersStopped())
{
logger.LogInformation("Waiting for all workers to stop...");
await Task.Delay(1000, stoppingToken);
@@ -142,7 +151,7 @@ public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguratio
/// </summary>
private async Task<WorkerServiceStatus> GetOrCreateInitialStatusRecord()
{
- var entry = _dbContext.WorkerServiceStatuses.FirstOrDefault(x => x.ServiceName == config.ServiceName);
+ var entry = _dbContext.WorkerServiceStatuses.FirstOrDefault(x => x.ServiceName == globalServiceStatus.ServiceName);
if (entry != null)
{
return entry;
@@ -150,7 +159,7 @@ public class StatusWorker(ILogger<StatusWorker> logger, WorkerStatusConfiguratio
entry = new WorkerServiceStatus
{
- ServiceName = config.ServiceName,
+ ServiceName = globalServiceStatus.ServiceName,
CurrentStatus = "Started",
DesiredStatus = string.Empty,
};
diff --git a/src/Utilities/AliasVault.WorkerStatus/WorkerStatusConfiguration.cs b/src/Utilities/AliasVault.WorkerStatus/WorkerStatusConfiguration.cs
deleted file mode 100644
index 8544c0db7..000000000
--- a/src/Utilities/AliasVault.WorkerStatus/WorkerStatusConfiguration.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="WorkerStatusConfiguration.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.WorkerStatus;
-
-/// <summary>
-/// Interface for the WorkerStatusDbContext.
-/// </summary>
-public class WorkerStatusConfiguration
-{
- /// <summary>
- /// Gets or sets the GlobalServiceStatus for the WorkerStatusDbContext.
- /// </summary>
- public GlobalServiceStatus GlobalServiceStatus { get; set; } = null!;
-
- /// <summary>
- /// Gets or sets the ServiceName for the WorkerStatusDbContext.
- /// </summary>
- public string ServiceName { get; set; } = null!;
-}