Skip to content

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

Refactor service control in admin, add TaskRunner (#221)

Leendert de Borste655dcedb0a6
diff --git a/src/AliasVault.Admin/Main/Components/WorkerStatus/ServiceControl.razor b/src/AliasVault.Admin/Main/Components/WorkerStatus/ServiceControl.razor
new file mode 100644
index 000000000..bfc2bdae0
--- /dev/null
+++ b/src/AliasVault.Admin/Main/Components/WorkerStatus/ServiceControl.razor
@@ -0,0 +1,240 @@
+@using AliasVault.WorkerStatus.Database
+@inherits MainBase
+
+@foreach (var service in Services)
+{
+ <button @onclick="() => ServiceClick(service.Name)"
+ class="@GetServiceButtonClasses(service) mx-3 inline-flex items-center justify-center rounded-xl px-8 py-2 text-white"
+ disabled="@(!IsHeartbeatValid(service.LastHeartbeat))"
+ title="@GetButtonTooltip(service.LastHeartbeat)">
+ <span>@service.DisplayName</span>
+ @if (service.IsPending)
+ {
+ <svg class="animate-spin ml-2 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
+ </svg>
+ }
+ </button>
+}
+
+@code {
+ /// <summary>
+ /// The names of the services to display.
+ /// </summary>
+ [Parameter]
+ public List<string> ServiceNames { get; set; } = ["AliasVault.SmtpService", "AliasVault.TaskRunner"];
+
+ /// <summary>
+ /// The display names of the services to display.
+ /// </summary>
+ [Parameter]
+ public Dictionary<string, string> ServiceDisplayNames { get; set; } = new();
+
+ /// <summary>
+ /// The statuses of the services.
+ /// </summary>
+ private List<WorkerServiceStatus> ServiceStatus = [];
+
+ /// <summary>
+ /// Whether the page is initializing.
+ /// </summary>
+ private bool InitInProgress;
+
+ /// <summary>
+ /// The interval to refresh the page.
+ /// </summary>
+ private readonly int AutoRefreshInterval = 5000;
+ private CancellationTokenSource? _timerCancellationTokenSource;
+
+ /// <summary>
+ /// The state of a service.
+ /// </summary>
+ private class ServiceState
+ {
+ public string Name { get; set; } = "";
+ public string DisplayName { get; set; } = "";
+ public bool Status { get; set; }
+ public bool IsPending { get; set; }
+ public DateTime LastHeartbeat { get; set; }
+ }
+
+ private List<ServiceState> Services { get; set; } = [];
+
+ /// <inheritdoc />
+ protected override async Task OnInitializedAsync()
+ {
+ Services = ServiceNames.Select(name => new ServiceState
+ {
+ Name = name,
+ DisplayName = ServiceDisplayNames.GetValueOrDefault(name, name)
+ }).ToList();
+
+ await base.OnInitializedAsync();
+ }
+
+ /// <inheritdoc />
+ protected override async Task OnAfterRenderAsync(bool firstRender)
+ {
+ await base.OnAfterRenderAsync(firstRender);
+
+ if (firstRender)
+ {
+ _timerCancellationTokenSource = new CancellationTokenSource();
+ _ = RunPeriodicRefreshAsync(_timerCancellationTokenSource.Token);
+ }
+ }
+
+ /// <inheritdoc />
+ protected override void Dispose(bool disposing)
+ {
+ base.Dispose(disposing);
+
+ if (disposing)
+ {
+ _timerCancellationTokenSource?.Cancel();
+ _timerCancellationTokenSource?.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// Gets the CSS classes for a service button based on its current state.
+ /// </summary>
+ private string GetServiceButtonClasses(ServiceState service)
+ {
+ string buttonClass = "cursor-pointer ";
+
+ if (!IsHeartbeatValid(service.LastHeartbeat))
+ {
+ buttonClass += "bg-gray-600";
+ }
+ else if (service.Status)
+ {
+ buttonClass += "bg-green-600";
+ }
+ else
+ {
+ buttonClass += "bg-red-600";
+ }
+
+ return buttonClass;
+ }
+
+ /// <summary>
+ /// Gets the tooltip text for a service button based on its last heartbeat.
+ /// </summary>
+ private string GetButtonTooltip(DateTime lastHeartbeat)
+ {
+ return IsHeartbeatValid(lastHeartbeat) ? "" : "Heartbeat offline";
+ }
+
+ /// <summary>
+ /// Checks if the heartbeat is valid (within the last 5 minutes).
+ /// </summary>
+ private bool IsHeartbeatValid(DateTime lastHeartbeat)
+ {
+ return DateTime.Now <= lastHeartbeat.AddMinutes(5);
+ }
+
+ /// <summary>
+ /// Handles a click on a service button.
+ /// </summary>
+ private async Task ServiceClick(string serviceName)
+ {
+ var service = Services.First(s => s.Name == serviceName);
+
+ if (!IsHeartbeatValid(service.LastHeartbeat))
+ {
+ return;
+ }
+
+ service.IsPending = true;
+ StateHasChanged();
+
+ service.Status = !service.Status;
+ await UpdateServiceStatus(serviceName, service.Status);
+
+ service.IsPending = false;
+ StateHasChanged();
+ }
+
+ /// <summary>
+ /// Initializes the page.
+ /// </summary>
+ private async Task InitPage()
+ {
+ if (InitInProgress || Services.Any(s => s.IsPending))
+ {
+ return;
+ }
+
+ try
+ {
+ InitInProgress = true;
+ var dbContext = await DbContextFactory.CreateDbContextAsync();
+ ServiceStatus = await dbContext.WorkerServiceStatuses.ToListAsync();
+
+ foreach (var service in Services)
+ {
+ var entry = ServiceStatus.Find(x => x.ServiceName == service.Name);
+ if (entry != null)
+ {
+ service.LastHeartbeat = entry.Heartbeat;
+ service.Status = IsHeartbeatValid(service.LastHeartbeat) && entry.CurrentStatus == "Started";
+ }
+ }
+
+ await InvokeAsync(StateHasChanged);
+ }
+ finally
+ {
+ InitInProgress = false;
+ }
+ }
+
+ /// <summary>
+ /// Updates the status of a service.
+ /// </summary>
+ private async Task<bool> UpdateServiceStatus(string serviceName, bool newStatus)
+ {
+ var dbContext = await DbContextFactory.CreateDbContextAsync();
+ var entry = await dbContext.WorkerServiceStatuses.Where(x => x.ServiceName == serviceName).FirstOrDefaultAsync();
+ if (entry != null)
+ {
+ string newDesiredStatus = newStatus ? "Started" : "Stopped";
+ entry.DesiredStatus = newDesiredStatus;
+ await dbContext.SaveChangesAsync();
+
+ var timeout = DateTime.Now.AddSeconds(30);
+ while (true)
+ {
+ if (DateTime.Now > timeout)
+ {
+ return false;
+ }
+
+ dbContext = await DbContextFactory.CreateDbContextAsync();
+ var check = await dbContext.WorkerServiceStatuses.Where(x => x.ServiceName == serviceName).FirstAsync();
+ if (check.CurrentStatus == newDesiredStatus)
+ {
+ return true;
+ }
+ await Task.Delay(1000);
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Refreshes the service status periodically.
+ /// </summary>
+ private async Task RunPeriodicRefreshAsync(CancellationToken cancellationToken)
+ {
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ await InitPage();
+ await Task.Delay(AutoRefreshInterval, cancellationToken);
+ }
+ }
+}
diff --git a/src/AliasVault.Admin/Main/Components/WorkerStatus/Services.razor b/src/AliasVault.Admin/Main/Components/WorkerStatus/Services.razor
deleted file mode 100644
index d5927a92f..000000000
--- a/src/AliasVault.Admin/Main/Components/WorkerStatus/Services.razor
+++ /dev/null
@@ -1,209 +0,0 @@
-@using AliasVault.WorkerStatus.Database
-@inherits MainBase
-
-<button @onclick="SmtpClick"
- class="@GetSmtpButtonClasses() mx-3 inline-flex items-center justify-center rounded-xl px-8 py-2 text-white"
- disabled="@(!IsHeartbeatValid())"
- title="@GetButtonTooltip()">
- <span>SmtpService</span>
- @if (SmtpPending)
- {
- <svg class="animate-spin ml-2 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
- <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
- </svg>
- }
-</button>
-
-@code {
- private List<WorkerServiceStatus> ServiceStatus = [];
- private bool InitInProgress;
- private bool SmtpStatus;
- private bool SmtpPending;
- private DateTime LastHeartbeat;
-
- /// <summary>
- /// The interval in milliseconds for refreshing the service status.
- /// </summary>
- private readonly int AutoRefreshInterval = 5000;
-
- /// <summary>
- /// CancellationTokenSource for the timer.
- /// </summary>
- private CancellationTokenSource? _timerCancellationTokenSource;
-
- /// <inheritdoc />
- protected override async Task OnAfterRenderAsync(bool firstRender)
- {
- await base.OnAfterRenderAsync(firstRender);
-
- if (firstRender)
- {
- _timerCancellationTokenSource = new CancellationTokenSource();
- _ = RunPeriodicRefreshAsync(_timerCancellationTokenSource.Token);
- }
- }
-
- /// <summary>
- /// Refreshes the service status periodically while waiting for specified amount of ms in between.
- /// </summary>
- private async Task RunPeriodicRefreshAsync(CancellationToken cancellationToken)
- {
- while (!cancellationToken.IsCancellationRequested)
- {
- await InitPage();
- await Task.Delay(AutoRefreshInterval, cancellationToken);
- }
- }
-
- /// <inheritdoc />
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
-
- if (disposing)
- {
- _timerCancellationTokenSource?.Cancel();
- _timerCancellationTokenSource?.Dispose();
- }
- }
-
- /// <summary>
- /// Gets the CSS classes for the SMTP button based on its current state.
- /// </summary>
- /// <returns>A string containing the CSS classes for the button.</returns>
- private string GetSmtpButtonClasses()
- {
- string buttonClass = "cursor-pointer ";
-
- if (!IsHeartbeatValid())
- {
- buttonClass += "bg-gray-600";
- }
- else if (SmtpStatus)
- {
- buttonClass += "bg-green-600";
- }
- else
- {
- buttonClass += "bg-red-600";
- }
-
- return buttonClass;
- }
-
- /// <summary>
- /// Gets the tooltip text for the SMTP button.
- /// </summary>
- /// <returns>A string containing the tooltip text.</returns>
- private string GetButtonTooltip()
- {
- return IsHeartbeatValid() ? "" : "Heartbeat offline";
- }
-
- /// <summary>
- /// Checks if the heartbeat is valid (within the last 5 minutes).
- /// </summary>
- /// <returns>True if the heartbeat is valid, false otherwise.</returns>
- private bool IsHeartbeatValid()
- {
- return DateTime.Now <= LastHeartbeat.AddMinutes(5);
- }
-
- /// <summary>
- /// Handles the click event for the SMTP button.
- /// </summary>
- private async void SmtpClick()
- {
- if (!IsHeartbeatValid())
- {
- return;
- }
-
- SmtpPending = true;
- StateHasChanged();
-
- SmtpStatus = !SmtpStatus;
- await UpdateSmtpStatus(SmtpStatus);
-
- SmtpPending = false;
- StateHasChanged();
- }
-
- /// <summary>
- /// Initializes the page by fetching service statuses and updating the SMTP status.
- /// </summary>
- private async Task InitPage()
- {
- if (InitInProgress || SmtpPending)
- {
- return;
- }
-
- try
- {
- InitInProgress = true;
- var dbContext = await DbContextFactory.CreateDbContextAsync();
- ServiceStatus = await dbContext.WorkerServiceStatuses.ToListAsync();
-
- var smtpEntry = ServiceStatus.Find(x => x.ServiceName == "AliasVault.SmtpService");
- if (smtpEntry != null)
- {
- LastHeartbeat = smtpEntry.Heartbeat;
- SmtpStatus = IsHeartbeatValid() && smtpEntry.CurrentStatus == "Started";
- }
-
- await InvokeAsync(StateHasChanged);
- }
- finally
- {
- InitInProgress = false;
- }
- }
-
- /// <summary>
- /// Update the service statuses.
- /// </summary>
- public async Task<bool> UpdateServiceStatus(string serviceName, bool newStatus)
- {
- // Refresh the DbContext to ensure we get the latest data.
- var dbContext = await DbContextFactory.CreateDbContextAsync();
- var entry = await dbContext.WorkerServiceStatuses.Where(x => x.ServiceName == serviceName).FirstOrDefaultAsync();
- if (entry != null)
- {
- string newDesiredStatus = newStatus ? "Started" : "Stopped";
- entry.DesiredStatus = newDesiredStatus;
- await dbContext.SaveChangesAsync();
-
- // Wait for service to have updated its status.
- var timeout = DateTime.Now.AddSeconds(30);
- while (true)
- {
- if (DateTime.Now > timeout)
- {
- // Timeout
- return false;
- }
-
- dbContext = await DbContextFactory.CreateDbContextAsync();
- var check = await dbContext.WorkerServiceStatuses.Where(x => x.ServiceName == serviceName).FirstAsync();
- if (check.CurrentStatus == newDesiredStatus)
- {
- // Done
- return true;
- }
- await Task.Delay(1000);
- }
- }
-
- return false;
- }
-
- /// <summary>
- /// Update the SMTP service status.
- /// </summary>
- public async Task<bool> UpdateSmtpStatus(bool newStatus)
- {
- return await UpdateServiceStatus("AliasVault.SmtpService", newStatus);
- }
-}
diff --git a/src/AliasVault.Admin/Main/Layout/TopMenu.razor b/src/AliasVault.Admin/Main/Layout/TopMenu.razor
index 85f30c712..829016ea1 100644
--- a/src/AliasVault.Admin/Main/Layout/TopMenu.razor
+++ b/src/AliasVault.Admin/Main/Layout/TopMenu.razor
@@ -32,8 +32,13 @@
</div>
</div>
<div class="flex justify-end items-center lg:order-2">
- <Services />
- <button id="theme-toggle" data-tooltip-target="tooltip-toggle" type="button" class="text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:outline-none focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-700 rounded-lg text-sm p-2.5">
+ <ServiceControl ServiceNames="@(new List<string> { "AliasVault.SmtpService", "AliasVault.TaskRunner" })"
+ ServiceDisplayNames="@(new Dictionary<string, string>
+ {
+ { "AliasVault.SmtpService", "Smtp" },
+ { "AliasVault.TaskRunner", "Tasks" }
+ })" />
+ <button id="theme-toggle" data-tooltip-target="tooltip-toggle" type="button" class="text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:outline-none focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-700 rounded-lg text-sm p-2.5">
<svg id="theme-toggle-dark-icon" class="hidden w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"></path></svg>
<svg id="theme-toggle-light-icon" class="hidden w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" fill-rule="evenodd" clip-rule="evenodd"></path></svg>
</button>