Completes the scheduled jobs module with default jobs, a themed scheduler page and aligned recovery semantics

This commit is contained in:
BinaryAlley committed 2026-09-04 13:56:04 -07:00
1 parent 99a6159f7f
commit 4b7cfbbe11
67 files changed
+3324 -745

No files matched your search

@@ -18,12 +18,26 @@ public interface IScheduledJobRuntimeRegistry
/// <returns><see langword="true"/> when the cycle was started, <see langword="false"/> when a cycle was already running.</returns>
bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource);
/// <summary>
/// Gets a value indicating whether the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/> is currently running.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is checked.</param>
/// <returns><see langword="true"/> when a cycle is currently running, <see langword="false"/> otherwise.</returns>
bool HasActiveCycle(ScheduledJobId scheduledJobId);
/// <summary>
/// Stops the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is stopped.</param>
void StopCycle(ScheduledJobId scheduledJobId);
/// <summary>
/// Ends the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>, when it was started with <paramref name="cycleCancellationTokenSource"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is ended.</param>
/// <param name="cycleCancellationTokenSource">The cancellation token source of the cycle that is ending.</param>
void EndCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource);
/// <summary>
/// Attempts to reserve the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
@@ -16,10 +16,28 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
/// </summary>
private sealed class ScheduledJobRuntimeState
{
/// <summary>
/// Object used to synchronize the access to the runtime state of the scheduled job.
/// </summary>
public readonly object SyncRoot = new();
/// <summary>
/// Gets or sets the cancellation token source of the running execution cycle, or <see langword="null"/> when no cycle is running.
/// </summary>
public CancellationTokenSource? CycleCancellationTokenSource;
/// <summary>
/// Gets the slot that guards a scheduled job against overlapping executions.
/// </summary>
public readonly SemaphoreSlim RunSlot = new(1, 1);
}
// One runtime state instance exists per scheduled job, and it is shared by every thread that works on that job: the
// cycle worker of the job, the request handlers that stop or remove the job, and the one time (fired) executions. The
// ConcurrentDictionary only makes the lookup of the state instance itself thread safe; the fields of the instance are
// still plain mutable fields, so every read or write of them is guarded by the per-state lock. The lock is only ever
// held for the few instructions that mutate or read the state, never while a cancellation callback runs, and the lock
// is reentrant for the thread that owns it, which keeps the registry free of deadlocks.
private readonly ConcurrentDictionary<ScheduledJobId, ScheduledJobRuntimeState> _runtimeStates = [];
/// <summary>
@@ -31,10 +49,31 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
public bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource)
{
ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState());
if (state.CycleCancellationTokenSource is not null)
lock (state.SyncRoot)
{
// The check and the assignment must be one atomic step: without the lock, two concurrent starts of the same job could both observe that
// no cycle is running and both store their own cancellation token source, so a job would end up with two live cycles at once.
// The lock serializes the starts, so exactly one wins.
if (state.CycleCancellationTokenSource is not null)
return false;
state.CycleCancellationTokenSource = cycleCancellationTokenSource;
return true;
}
}
/// <summary>
/// Gets a value indicating whether the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/> is currently running.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is checked.</param>
/// <returns><see langword="true"/> when a cycle is currently running, <see langword="false"/> otherwise.</returns>
public bool HasActiveCycle(ScheduledJobId scheduledJobId)
{
if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
return false;
state.CycleCancellationTokenSource = cycleCancellationTokenSource;
return true;
// The read takes the same lock the writers use, so it never observes a partially updated state, and the lock also acts as the memory barrier
// that guarantees the read sees the latest value written by another thread.
lock (state.SyncRoot)
return state.CycleCancellationTokenSource is not null;
}
/// <summary>
@@ -45,11 +84,43 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
{
if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
return;
CancellationTokenSource? cycleCancellationTokenSource = state.CycleCancellationTokenSource;
state.CycleCancellationTokenSource = null;
CancellationTokenSource? cycleCancellationTokenSource;
lock (state.SyncRoot)
{
// The stored token source is read and cleared while the lock is held, so that a start that races with this stop either sees the cycle and loses,
// or sees no cycle and starts a fresh one whose token source is not the one cancelled here.
cycleCancellationTokenSource = state.CycleCancellationTokenSource;
state.CycleCancellationTokenSource = null;
}
// Cancelling a token source synchronously invokes every callback registered on its token, and those callbacks can reach back into this registry
// (for example the cycle worker that unwinds and ends its own cycle). The lock is therefore released before the cancellation runs,
// so no callback ever executes while the lock is held, and the lock is never held longer than the few instructions that mutate the state.
cycleCancellationTokenSource?.Cancel();
}
/// <summary>
/// Ends the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>, when it was started with <paramref name="cycleCancellationTokenSource"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is ended.</param>
/// <param name="cycleCancellationTokenSource">The cancellation token source of the cycle that is ending.</param>
/// <remarks>
/// The cycle worker calls this method when its cycle finishes, so that a cycle that was replaced by a newer one
/// after being stopped can never cancel the cycle that replaced it.
/// </remarks>
public void EndCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource)
{
if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
lock (state.SyncRoot)
// The identity check matters for the stop-then-start race: when a worker is stopped and a newer cycle is started before the old worker reaches
// its cleanup, the stored token source already belongs to the new cycle. The old worker must only clear the field when it still owns it,
// so it can never cancel the cycle that replaced it.
if (ReferenceEquals(state.CycleCancellationTokenSource, cycleCancellationTokenSource))
state.CycleCancellationTokenSource = null;
// Cancelling the worker's own token source is always safe and idempotent, and runs outside the lock for the same reason as in StopCycle:
// the cancellation callbacks must not execute while the lock is held.
cycleCancellationTokenSource.Cancel();
}
/// <summary>
/// Attempts to reserve the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
@@ -58,7 +129,10 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
public bool TryAcquireRunSlot(ScheduledJobId scheduledJobId)
{
ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState());
return state.RunSlot.Wait(0);
lock (state.SyncRoot)
// The slot is acquired under the same lock that guards the rest of the state, so the acquire is serialized
// with the cycle start and end transitions of the job; Wait(0) never blocks, so the lock is held only for a single non blocking instruction.
return state.RunSlot.Wait(0);
}
/// <summary>
@@ -67,7 +141,12 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution slot is released.</param>
public void ReleaseRunSlot(ScheduledJobId scheduledJobId)
{
if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
state.RunSlot.Release();
if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
return;
lock (state.SyncRoot)
// The semaphore is only released when a slot is actually taken, which is checked under the same lock as the acquire;
// without that check, releasing a slot that was never acquired, or releasing it twice, would throw a SemaphoreFullException.
if (state.RunSlot.CurrentCount is 0)
state.RunSlot.Release();
}
}
@@ -108,7 +108,20 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
return;
}
foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value)
RunCycleWorkerAsync(ScheduledJobId.Create(scheduledJob.Id), runImmediately: false, cancellationToken).FireAndForgetSafeAsync();
{
ScheduledJobId scheduledJobId = ScheduledJobId.Create(scheduledJob.Id);
// A scheduled job that was running when the application shut down had its execution interrupted, so its open
// execution history row is closed and its status is reset before its cycle is resumed.
if (scheduledJob.Status == ScheduledJobStatus.Running)
{
ScheduledJobStatus reconciledStatus = await ReconcileInterruptedRunAsync(scheduledJobId, cancellationToken).ConfigureAwait(false);
if (reconciledStatus != ScheduledJobStatus.Active)
continue;
}
// A once at startup scheduled job fires immediately when its cycle is resumed at startup; the other scheduled jobs wait for their next scheduled execution.
bool runImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup;
RunCycleWorkerAsync(scheduledJobId, runImmediately, cancellationToken).FireAndForgetSafeAsync();
}
}
/// <summary>
@@ -119,47 +132,69 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken)
{
CancellationTokenSource cycleCancellationTokenSource = new();
// Each cycle owns its own cancellation token source: it is the handle the runtime registry stores, so stopping one
// scheduled job cancels exactly this cycle and no other job's cycle, even though the cycle worker itself runs "fire and forget" on another thread.
using CancellationTokenSource cycleCancellationTokenSource = new();
// A scheduled job has at most one live cycle, and starts are "fire and forget", so when the registry already holds a
// cycle for the job, there is nothing for this worker to do and the existing cycle keeps ticking.
if (!_runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource))
{
cycleCancellationTokenSource.Dispose();
return;
}
try
{
CancellationToken cycleToken = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, cycleCancellationTokenSource.Token).Token;
// The cycle token is cancelled when the application shuts down (through the host stopping token) or when this cycle is stopped
// (through its own token source), so a single token lets every await of the cycle observe both stop paths.
using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, cycleCancellationTokenSource.Token);
CancellationToken cycleToken = linkedCancellationTokenSource.Token;
// An immediate run is executed as a cycle run, so it completes the scheduled job back to its active state and is
// recorded as part of the cycle; this is the path taken by an admin start, by the resume at startup and by the seed of the default jobs.
if (runImmediately)
await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false);
// The schedule is read from the storage medium for every cycle, so the delay until the next run is always
// computed from the persisted schedule; when the scheduled job can no longer be read, the cycle simply ends.
Schedule? schedule = await GetScheduleAsync(scheduledJobId, cycleToken).ConfigureAwait(false);
if (schedule is null)
return;
// A once at startup schedule fires its task exactly once when its cycle starts, at the application startup; the cycle
// then ends, and the scheduled job stays active, so its cycle is started again at the next application startup.
if (schedule.ScheduleType == ScheduleType.OnceAtStartup)
return;
while (true)
TimeSpan delay = await CalculateDelayAsync(schedule).ConfigureAwait(false);
// The periodic timer owns the cadence of the cycle: an interval schedule ticks every interval, and a daily
// schedule ticks after the delay until the next daily hour and minute.
using PeriodicTimer timer = new(delay);
// Each iteration waits for the next tick, runs the task and loops; a cancelled token or a disposed timer makes WaitForNextTickAsync exit,
// which ends the cycle through the finally block below.
while (await timer.WaitForNextTickAsync(cycleToken).ConfigureAwait(false))
{
TimeSpan delay = await CalculateDelayAsync(schedule).ConfigureAwait(false);
using PeriodicTimer timer = new(delay);
while (await timer.WaitForNextTickAsync(cycleToken).ConfigureAwait(false))
{
if (cycleToken.IsCancellationRequested)
return;
await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false);
// A daily schedule needs its delay recalculated after every run, so the next run happens at the next day's hour and minute.
if (schedule.ScheduleType == ScheduleType.DailyAtHourAndMinute)
timer.Period = await CalculateDelayAsync(schedule).ConfigureAwait(false);
}
if (cycleToken.IsCancellationRequested)
return;
// The run is awaited inside the tick and the periodic timer does not queue missed ticks, so a task that
// outlasts its interval drops the missed ticks instead of piling them up; the run slot acquired inside
// RunScheduledJobAsync is the second guard against overlapping executions.
await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false);
// A daily schedule needs its delay recalculated after every run from the current time, so the next run
// happens at the next day's hour and minute, also across daylight saving time changes.
if (schedule.ScheduleType == ScheduleType.DailyAtHourAndMinute)
timer.Period = await CalculateDelayAsync(schedule).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { }
catch (OperationCanceledException)
{
// A cancelled cycle is the normal way the loop ends when the cycle is stopped or the application shuts down, so it is not an error and must not be logged as one.
}
catch (Exception exception)
{
// Failures of a single run are handled inside RunScheduledJobAsync, so an exception reaching this point is unexpected and ends the cycle.
_logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value);
}
finally
{
_runtimeRegistry.StopCycle(scheduledJobId);
cycleCancellationTokenSource.Dispose();
// The registry is always told that the cycle ended, because every exit path passes through here, including the
// early returns above; EndCycle cancels and deregisters the cycle, and the outer using disposes the token source.
_runtimeRegistry.EndCycle(scheduledJobId, cycleCancellationTokenSource);
}
}
@@ -196,6 +231,15 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
{
await ExecuteScheduledJobRunAsync(scheduledJobId, isCycleRun, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// An execution that was cancelled is a normal outcome when the cycle of the scheduled job is stopped or the application shuts down.
}
catch (Exception exception)
{
_logger.LogError(exception, "The execution of the scheduled job '{ScheduledJobId}' failed unexpectedly.", scheduledJobId.Value);
await ReconcileInterruptedRunAsync(scheduledJobId, CancellationToken.None).ConfigureAwait(false);
}
finally
{
_runtimeRegistry.ReleaseRunSlot(scheduledJobId);
@@ -226,27 +270,136 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return;
Result<Success> startExecutionResult = scheduledJobDomainResult.Value.MarkExecutionStarted(isCycleRun);
ScheduledJob scheduledJob = scheduledJobDomainResult.Value;
Result<Success> startExecutionResult = scheduledJob.MarkExecutionStarted(isCycleRun);
if (startExecutionResult.IsFailure)
return;
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents())
await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
// Execute the payload of the task of the scheduled job.
IScheduledTaskExecutorFactory taskExecutorFactory = services.GetRequiredService<IScheduledTaskExecutorFactory>();
IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJobDomainResult.Value.TaskType);
Result<Success> executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJobDomainResult.Value, cancellationToken).ConfigureAwait(false);
if (executePayloadResult.IsFailure)
_logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJobDomainResult.Value.Name, executePayloadResult.FirstError.Description);
// Mark the task as completed. The same domain entity is reused, because it alone still tracks the run id of the
// current execution, which is required to raise the completion domain event; a fresh copy reloaded from the
// storage medium would no longer know which execution to complete.
Result<Success> completeExecutionResult = scheduledJobDomainResult.Value.MarkExecutionCompleted(isCycleRun);
if (completeExecutionResult.IsFailure)
// Execute the payload of the task of the scheduled job; a payload failure is a normal outcome that is logged, while a
// thrown exception is logged as well, so that the run is still completed instead of leaving the scheduled job running.
try
{
if (cancellationToken.IsCancellationRequested)
return;
IScheduledTaskExecutorFactory taskExecutorFactory = services.GetRequiredService<IScheduledTaskExecutorFactory>();
IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJob.TaskType);
Result<Success> executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJob, cancellationToken).ConfigureAwait(false);
if (executePayloadResult.IsFailure)
_logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJob.Name, executePayloadResult.FirstError.Description);
}
catch (OperationCanceledException)
{
return;
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
_logger.LogError(exception, "The task of the scheduled job '{ScheduledJobName}' threw an exception.", scheduledJob.Name);
}
if (cancellationToken.IsCancellationRequested)
return;
await CompleteExecutionAsync(scheduledJob, unitOfWork, domainEventPublisher, isCycleRun, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Completes the execution of the task of <paramref name="scheduledJob"/>, when the scheduled job is still running.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task execution is completed.</param>
/// <param name="unitOfWork">The unit of work of the current run, whose tracked entities are reused by the completion handlers.</param>
/// <param name="domainEventPublisher">The publisher used to publish the completion domain events.</param>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task CompleteExecutionAsync(ScheduledJob scheduledJob, IUnitOfWork unitOfWork, IDomainEventPublisher domainEventPublisher, bool isCycleRun, CancellationToken cancellationToken)
{
try
{
// Reload the scheduled job from the storage medium without tracking, because a stop or a removal that happened while the
// task was executing already reset its state, and completing the execution here would silently undo that change.
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdWithoutTrackingAsync(scheduledJob.Id.Value, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return;
if (getScheduledJobResult.Value.Status != ScheduledJobStatus.Running)
return;
// A one time execution returns the scheduled job to its active state when its execution cycle is still running, so the
// running cycle keeps scheduling executions and the job can still be stopped; the same applies to a once at startup job,
// whose active state is what makes it fire again at the next application startup.
bool completesTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup;
Result<Success> completeExecutionResult = scheduledJob.MarkExecutionCompleted(completesTheCycleRun);
if (completeExecutionResult.IsFailure)
return;
foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents())
await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
catch (Exception exception)
{
// The completion failed after the execution was persisted as running, so the interrupted run is reconciled directly.
_logger.LogError(exception, "Failed to complete the execution of the scheduled job '{ScheduledJobId}'.", scheduledJob.Id.Value);
await ReconcileInterruptedRunAsync(scheduledJob.Id, CancellationToken.None).ConfigureAwait(false);
}
}
/// <summary>
/// Reconciles the scheduled job identified by <paramref name="scheduledJobId"/> when its execution was interrupted: its open
/// execution history row is closed, and the scheduled job is returned to a status from which it can run again.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose interrupted execution is reconciled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The status the scheduled job was reconciled to, or its current status when no reconciliation was needed.</returns>
private async Task<ScheduledJobStatus> ReconcileInterruptedRunAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
{
try
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return ScheduledJobStatus.Added;
ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
// A scheduled job that is not running needs no reconciliation.
if (scheduledJob.Status != ScheduledJobStatus.Running)
return scheduledJob.Status;
// An interrupted execution returns the scheduled job to its active state when its execution cycle was active
// when the execution started, so its cycle is resumed at startup; an interrupted execution of a job whose cycle
// was not active returns it to its added state. The cycle active state is read from the execution history row
// and not from the IsCycleRun flag, so that a manually fired one time execution on an active job keeps its
// manual audit trail while its cycle is still resumed.
Result<ScheduledJobExecutionEntity?> getOpenExecutionResult = await unitOfWork.ScheduledJobExecutionRepository
.GetOpenByScheduledJobIdAsync(scheduledJob.Id, cancellationToken).ConfigureAwait(false);
if (getOpenExecutionResult.IsFailure)
return ScheduledJobStatus.Added;
ScheduledJobExecutionEntity? openExecution = getOpenExecutionResult.Value;
ScheduledJobStatus reconciledStatus = (openExecution?.WasCycleActive ?? true) ? ScheduledJobStatus.Active : ScheduledJobStatus.Added;
Result<Updated> updateScheduledJobResult = await unitOfWork.ScheduledJobRepository.UpdateAsync(
CreateUpdatedScheduledJob(scheduledJob, reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
if (updateScheduledJobResult.IsFailure)
return ScheduledJobStatus.Added;
if (openExecution is not null)
{
Result<Updated> updateExecutionResult = await unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(
CreateClosedExecution(openExecution, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
if (updateExecutionResult.IsFailure)
return ScheduledJobStatus.Added;
}
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
_logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name);
return reconciledStatus;
}
catch (OperationCanceledException)
{
return ScheduledJobStatus.Added;
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Failed to reconcile the interrupted execution of the scheduled job '{ScheduledJobId}'.", scheduledJobId.Value);
return ScheduledJobStatus.Added;
}
}
/// <summary>
@@ -278,4 +431,58 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
// The daily hour and minute of a schedule are expressed in the local time of the server, so that a daily schedule follows the clock the server runs on.
return schedule.GetDelayUntilNextExecution(dateTimeProvider.UtcNow, TimeZoneInfo.Local);
}
/// <summary>
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
/// </summary>
/// <param name="scheduledJob">The scheduled job to copy.</param>
/// <param name="status">The status of the copy.</param>
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
/// <returns>The copy of the scheduled job.</returns>
private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc)
{
return new ScheduledJobEntity
{
Id = scheduledJob.Id,
Name = scheduledJob.Name,
TaskType = scheduledJob.TaskType,
ScheduleType = scheduledJob.ScheduleType,
IntervalMinutes = scheduledJob.IntervalMinutes,
Hour = scheduledJob.Hour,
Minute = scheduledJob.Minute,
Status = status,
OwnerUserId = scheduledJob.OwnerUserId,
LastStartedOnUtc = lastStartedOnUtc,
LastCompletedOnUtc = lastCompletedOnUtc,
CreatedOnUtc = scheduledJob.CreatedOnUtc,
CreatedBy = scheduledJob.CreatedBy,
UpdatedOnUtc = scheduledJob.UpdatedOnUtc,
UpdatedBy = scheduledJob.UpdatedBy
};
}
/// <summary>
/// Creates a copy of <paramref name="execution"/> with the provided completion time.
/// </summary>
/// <param name="execution">The execution to copy.</param>
/// <param name="completedOnUtc">The completion time of the copy.</param>
/// <returns>The copy of the execution.</returns>
private static ScheduledJobExecutionEntity CreateClosedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc)
{
return new ScheduledJobExecutionEntity
{
Id = execution.Id,
ScheduledJobId = execution.ScheduledJobId,
TaskType = execution.TaskType,
IsCycleRun = execution.IsCycleRun,
WasCycleActive = execution.WasCycleActive,
StartedOnUtc = execution.StartedOnUtc,
CompletedOnUtc = completedOnUtc,
CreatedOnUtc = execution.CreatedOnUtc,
CreatedBy = execution.CreatedBy,
UpdatedOnUtc = execution.UpdatedOnUtc,
UpdatedBy = execution.UpdatedBy
};
}
}
@@ -34,6 +34,8 @@ public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory
{
ScheduledTaskType.ScanMediaLibraries => _serviceProvider.GetRequiredService<MediaLibraryScanTaskExecutor>(),
ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService<TemporaryFilesCleanupTaskExecutor>(),
ScheduledTaskType.RepairThemes => _serviceProvider.GetRequiredService<RepairThemesTaskExecutor>(),
ScheduledTaskType.CleanScheduledJobExecutionHistory => _serviceProvider.GetRequiredService<CleanScheduledJobExecutionHistoryTaskExecutor>(),
_ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType))
};
}
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Task executor that cleans the execution history of the scheduled jobs, keeping only the executions of the past month.
/// </summary>
public class CleanScheduledJobExecutionHistoryTaskExecutor : IScheduledTaskExecutor
{
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<CleanScheduledJobExecutionHistoryTaskExecutor> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="CleanScheduledJobExecutionHistoryTaskExecutor"/> class.
/// </summary>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="logger">Injected service for logging.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public CleanScheduledJobExecutionHistoryTaskExecutor(IDateTimeProvider dateTimeProvider, ILogger<CleanScheduledJobExecutionHistoryTaskExecutor> logger, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_dateTimeProvider = dateTimeProvider;
_logger = logger;
}
/// <summary>
/// Removes the executions of the tasks of the scheduled jobs that are older than a month, keeping only the recent executions for audit.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task is executed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken)
{
DateTime cutoffUtc = _dateTimeProvider.UtcNow.AddMonths(-1);
Result<Success> deleteResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteOlderThanAsync(cutoffUtc, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
_logger.LogInformation("Cleaned the execution history of the scheduled jobs on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success;
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Infrastructure.Core.Themes;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Task executor that repairs the installed themes whose files are missing.
/// </summary>
public class RepairThemesTaskExecutor : IScheduledTaskExecutor
{
private readonly IThemeService _themeService;
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<RepairThemesTaskExecutor> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="RepairThemesTaskExecutor"/> class.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="logger">Injected service for logging.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public RepairThemesTaskExecutor(IThemeService themeService, ILogger<RepairThemesTaskExecutor> logger, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_logger = logger;
}
/// <summary>
/// Repairs the installed themes whose files are missing, reinstalling the files of the bundled themes from their shipped archives.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task is executed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken)
{
// Repairs are best effort, so a failure to repair one theme is logged inside the synchronizer and the remaining themes are still repaired.
try
{
await ThemeSynchronizer.SynchronizeAsync(_themeService, _unitOfWork, _logger, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Repaired the themes on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception exception)
{
_logger.LogWarning(exception, "The themes could not be repaired on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Error.Failure(description: nameof(RepairThemesTaskExecutor));
}
}
}
@@ -32,7 +32,7 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobsAsync(IReadOnlyList<ScheduledJobResponse> scheduledJobs, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false);
await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false);
}
/// <summary>
@@ -42,7 +42,7 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false);
await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false);
}
/// <summary>
@@ -52,6 +52,6 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false);
await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false);
}
}
@@ -17,6 +17,11 @@ namespace Lumina.Infrastructure.Core.Scheduling.Notifications;
[Authorize]
public class ScheduledJobsHub : Hub<IScheduledJobsClient>
{
/// <summary>
/// Name of the group that holds the connections of the verified administrator clients.
/// </summary>
public const string ADMINISTRATORS_GROUP = "Administrators";
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
@@ -40,6 +45,9 @@ public class ScheduledJobsHub : Hub<IScheduledJobsClient>
Context.Abort();
return;
}
// The connection is added to the administrator group only after the role check succeeded, so the notifications, which are
// broadcast to that group, can never reach a client whose connection was not verified to belong to an administrator.
await Groups.AddToGroupAsync(Context.ConnectionId, ADMINISTRATORS_GROUP).ConfigureAwait(false);
await base.OnConnectedAsync().ConfigureAwait(false);
}
@@ -5,8 +5,6 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@@ -19,76 +17,58 @@ using System.Threading.Tasks;
namespace Lumina.Infrastructure.Core.Themes;
/// <summary>
/// Background job that installs the bundled themes into the storage medium and the theme storage at startup.
/// Utility class that keeps the installed themes in sync with the bundled theme archives.
/// </summary>
internal sealed class ThemeDetectionSyncJob : BackgroundService
internal static class ThemeSynchronizer
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IThemeService _themeService;
private readonly ILogger<ThemeDetectionSyncJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeDetectionSyncJob"/> class.
/// Installs the bundled themes into the storage medium and the theme storage, and repairs the installed themes whose files are missing.
/// </summary>
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="logger">Injected logger used for logging.</param>
public ThemeDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IThemeService themeService, ILogger<ThemeDetectionSyncJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_themeService = themeService;
_logger = logger;
}
/// <summary>
/// Method called when the background service starts.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken)
{
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken);
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure)
{
_logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
return;
}
// themes that were soft deleted by the user must not be reinstalled automatically
// Themes that were soft deleted by the user must not be reinstalled automatically.
List<ThemeEntity> themes = [.. getThemesResult.Value];
foreach (string archivePath in _themeService.GetBundledThemeArchivePaths())
foreach (string archivePath in themeService.GetBundledThemeArchivePaths())
{
Result<ThemeManifestDto> manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken);
Result<ThemeManifestDto> manifestResult = await themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken).ConfigureAwait(false);
if (manifestResult.IsFailure)
{
_logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description);
logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description);
continue;
}
ThemeEntity? existingTheme = themes.Where(theme => theme.ThemeId == manifestResult.Value.Id).FirstOrDefault();
// a theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme
// whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled
if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || _themeService.HasThemePack(existingTheme.ThemeId)))
// A theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme
// whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled.
if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || themeService.HasThemePack(existingTheme.ThemeId)))
continue;
// installing a bundled theme at startup is best effort: a file system failure here must never crash the host,
// because the default BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and
// disposes its service provider, making every later request fail
// Installing a bundled theme at startup is best effort: a file system failure here must never crash the host, because the default
// BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and disposes its service provider, making every later request fail.
try
{
await using FileStream archive = File.OpenRead(archivePath);
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(archive, cancellationToken);
Result<ThemeManifestDto> installResult = await themeService.InstallAsync(archive, cancellationToken).ConfigureAwait(false);
if (installResult.IsFailure)
{
_logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description);
logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description);
continue;
}
// a known theme only gets its missing files reinstalled, so no new row is inserted
// A known theme only gets its missing files reinstalled, so no new row is inserted.
if (existingTheme is not null)
continue;
@@ -108,40 +88,41 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
UpdatedBy = default
};
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken);
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
_logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
else
themes.Add(themeEntity);
}
catch (IOException exception)
{
_logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id);
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id);
}
catch (UnauthorizedAccessException exception)
{
_logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id);
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id);
}
}
await CleanUpMissingThemePacksAsync(unitOfWork, themes, cancellationToken);
await EnsureCurrentThemeExistsAsync(unitOfWork, themes, cancellationToken);
await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false);
await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false);
await unitOfWork.SaveChangesAsync(cancellationToken);
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Restores the files of the damaged bundled themes that were not deleted by the user, and removes the damaged themes whose files could not be recovered.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="logger">Injected logger used for logging.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
private static async Task CleanUpMissingThemePacksAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, ILogger logger, CancellationToken cancellationToken)
{
// a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored
// automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed
// externally, and is the only case where the files are restored
IReadOnlyList<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))];
// A soft deleted theme was deleted intentionally from the admin interface, so it must never be restored automatically;
// only a theme that was not deleted, but whose files went missing, was corrupted or removed externally, and is the only case where the files are restored.
IReadOnlyList<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !themeService.HasThemePack(theme.ThemeId))];
if (brokenThemes.Count is 0)
return;
@@ -151,39 +132,39 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
{
if (brokenTheme.InstallSource == ThemeInstallSource.Bundled)
{
// the files of a bundled theme that was not deleted by the user are restored from its shipped archive
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken);
// The files of a bundled theme that was not deleted by the user are restored from its shipped archive.
Result<Success> restoreResult = await themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken).ConfigureAwait(false);
if (restoreResult.IsSuccess)
continue;
_logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description);
logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description);
// at least one bundled theme must always remain available, so the application never ends up without any theme;
// the last remaining bundled theme is kept even when its files cannot be recovered
// At least one bundled theme must always remain available, so the application never ends up without any theme;
// the last remaining bundled theme is kept even when its files cannot be recovered.
int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled);
if (availableBundledThemes <= 1)
{
_logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId);
logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId);
continue;
}
// a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later
// A bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later.
brokenTheme.IsDeleted = true;
brokenTheme.IsCurrent = null;
brokenTheme.UpdatedOnUtc = DateTime.UtcNow;
brokenTheme.UpdatedBy = default;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken);
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
_logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
}
else
{
// a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely
_logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId);
// A user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely.
logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId);
brokenTheme.IsCurrent = null;
Result<Deleted> deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken);
Result<Deleted> deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
_logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
}
}
catch (OperationCanceledException)
@@ -192,9 +173,8 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
}
catch (Exception exception)
{
// repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host,
// so it is logged and the remaining broken themes are still processed
_logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId);
// Repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, so it is logged and the remaining broken themes are still processed.
logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId);
}
}
}
@@ -202,20 +182,21 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
/// <summary>
/// Activates the configured default theme when no theme is currently active, so the application always has an active theme.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
{
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
return;
// a theme whose files are present is preferred, so the activated theme can render immediately; a bundled theme
// whose files could not be restored is kept as the fallback, so the application always has an active theme
// A theme whose files are present is preferred, so the activated theme can render immediately; a bundled theme
// whose files could not be restored is kept as the fallback, so the application always has an active theme.
ThemeEntity? defaultTheme = themes
.Where(theme => !theme.IsDeleted)
.OrderBy(theme => _themeService.HasThemePack(theme.ThemeId) ? 0 : 1)
.ThenBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.OrderBy(theme => themeService.HasThemePack(theme.ThemeId) ? 0 : 1)
.ThenBy(theme => string.Equals(theme.ThemeId, themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (defaultTheme is null)
@@ -224,6 +205,6 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
defaultTheme.IsCurrent = true;
defaultTheme.UpdatedOnUtc = DateTime.UtcNow;
defaultTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken);
await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
}
}