#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System.Collections.Concurrent;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution;
///
/// Registry that holds the live runtime state of the scheduled jobs.
///
public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
{
///
/// Class that holds the live runtime state of the execution cycle of a scheduled job.
///
private sealed class ScheduledJobRuntimeState
{
public CancellationTokenSource? CycleCancellationTokenSource;
public readonly SemaphoreSlim RunSlot = new(1, 1);
}
private readonly ConcurrentDictionary _runtimeStates = [];
///
/// Starts the execution cycle of the scheduled job identified by .
///
/// The object representing the unique identifier of the scheduled job whose cycle is started.
/// The cancellation token source used to stop the execution cycle.
/// when the cycle was started, when a cycle was already running.
public bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource)
{
ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState());
if (state.CycleCancellationTokenSource is not null)
return false;
state.CycleCancellationTokenSource = cycleCancellationTokenSource;
return true;
}
///
/// Stops the execution cycle of the scheduled job identified by .
///
/// The object representing the unique identifier of the scheduled job whose cycle is stopped.
public void StopCycle(ScheduledJobId scheduledJobId)
{
if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
return;
CancellationTokenSource? cycleCancellationTokenSource = state.CycleCancellationTokenSource;
state.CycleCancellationTokenSource = null;
cycleCancellationTokenSource?.Cancel();
}
///
/// Attempts to reserve the execution slot of the scheduled job identified by .
///
/// The object representing the unique identifier of the scheduled job whose execution slot is reserved.
/// when the slot was reserved, when another execution is already running.
public bool TryAcquireRunSlot(ScheduledJobId scheduledJobId)
{
ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState());
return state.RunSlot.Wait(0);
}
///
/// Releases the execution slot of the scheduled job identified by .
///
/// The object representing the unique identifier of the scheduled job whose execution slot is released.
public void ReleaseRunSlot(ScheduledJobId scheduledJobId)
{
if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
state.RunSlot.Release();
}
}