199 lines
7.7 KiB
C#
199 lines
7.7 KiB
C#
using Ease.Core.Utility;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Options;
|
|
using System;
|
|
using System.Threading;
|
|
using System.Threading.Channels;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace HRM.UI.Realtime.Jobs
|
|
{
|
|
/// <summary>
|
|
/// Runs long work off the request thread and makes its progress visible in real time.
|
|
///
|
|
/// Usage from a controller action (copy what the work needs from CurrentUser first - there is no HttpContext later):
|
|
/// <code>
|
|
/// JobStartResult started = _jobRunner.Start(new JobRequest {
|
|
/// Key = "salary-process:" + payrollTypeId, Title = "Salary Process",
|
|
/// OwnerUserId = userId, PayrollTypeId = payrollTypeId, Audience = JobAudience.PayrollType,
|
|
/// Work = progress => service.DoTheWork(..., progress) });
|
|
/// return Ok(started.Job); // the browser follows it with RealtimeService.watchJob(runId)
|
|
/// </code>
|
|
/// </summary>
|
|
public interface IJobRunner
|
|
{
|
|
JobStartResult Start(JobRequest request);
|
|
|
|
/// <summary>A job's current state, checked against the viewer's rights.</summary>
|
|
JobAccess TryGet(string runId, int viewerUserId, int? viewerPayrollTypeId, out JobSnapshot snapshot);
|
|
|
|
/// <summary>The job of this key that is queued or running now (null when none), checked against the viewer's rights.</summary>
|
|
JobSnapshot GetActive(string key, int viewerUserId, int? viewerPayrollTypeId);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Queues jobs and is also the hosted service that runs them: a Channel feeds a loop that starts each job on its own
|
|
/// long-running task, at most RealtimeSettings.MaxConcurrentJobs at a time. Jobs are not cut off by the end of the
|
|
/// HTTP request; an application shutdown still ends them, exactly as it would end a long synchronous request.
|
|
/// </summary>
|
|
internal sealed class JobRunner : BackgroundService, IJobRunner
|
|
{
|
|
private readonly JobStore _store = new JobStore();
|
|
private readonly Channel<JobState> _queue = Channel.CreateUnbounded<JobState>(new UnboundedChannelOptions { SingleReader = true });
|
|
private readonly IRealtimePublisher _publisher;
|
|
private readonly RealtimeSettings _settings;
|
|
private readonly SemaphoreSlim _slots;
|
|
|
|
public JobRunner(IRealtimePublisher publisher, IOptions<RealtimeSettings> settings)
|
|
{
|
|
_publisher = publisher;
|
|
_settings = settings.Value;
|
|
_slots = new SemaphoreSlim(Math.Max(1, _settings.MaxConcurrentJobs));
|
|
}
|
|
|
|
public JobStartResult Start(JobRequest request)
|
|
{
|
|
if (request == null) throw new ArgumentNullException(nameof(request));
|
|
if (request.Work == null) throw new ArgumentException("A job needs Work.", nameof(request));
|
|
|
|
_store.Purge(TimeSpan.FromMinutes(Math.Max(1, _settings.FinishedJobRetentionMinutes)));
|
|
|
|
JobState state = _store.Register(request, out bool alreadyRunning);
|
|
if (!alreadyRunning)
|
|
{
|
|
lock (state.Sync)
|
|
{
|
|
state.Stage = "Waiting to start";
|
|
}
|
|
_queue.Writer.TryWrite(state);
|
|
}
|
|
|
|
JobSnapshot snapshot;
|
|
lock (state.Sync)
|
|
{
|
|
snapshot = state.ToSnapshot();
|
|
}
|
|
return new JobStartResult { Job = snapshot, AlreadyRunning = alreadyRunning };
|
|
}
|
|
|
|
public JobAccess TryGet(string runId, int viewerUserId, int? viewerPayrollTypeId, out JobSnapshot snapshot)
|
|
{
|
|
snapshot = null;
|
|
JobState state = _store.Get(runId);
|
|
if (state == null)
|
|
return JobAccess.NotFound;
|
|
if (!JobStore.CanView(state, viewerUserId, viewerPayrollTypeId))
|
|
return JobAccess.Forbidden;
|
|
lock (state.Sync)
|
|
{
|
|
snapshot = state.ToSnapshot();
|
|
}
|
|
return JobAccess.Ok;
|
|
}
|
|
|
|
public JobSnapshot GetActive(string key, int viewerUserId, int? viewerPayrollTypeId)
|
|
{
|
|
JobState state = _store.GetActive(key);
|
|
if (state == null || !JobStore.CanView(state, viewerUserId, viewerPayrollTypeId))
|
|
return null;
|
|
lock (state.Sync)
|
|
{
|
|
return state.ToSnapshot();
|
|
}
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
try
|
|
{
|
|
await foreach (JobState state in _queue.Reader.ReadAllAsync(stoppingToken))
|
|
{
|
|
await _slots.WaitAsync(stoppingToken);
|
|
_ = Task.Factory.StartNew(() =>
|
|
{
|
|
try
|
|
{
|
|
Execute(state, stoppingToken);
|
|
}
|
|
finally
|
|
{
|
|
_slots.Release();
|
|
}
|
|
},
|
|
CancellationToken.None,
|
|
TaskCreationOptions.LongRunning,
|
|
TaskScheduler.Default);
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// application is stopping
|
|
}
|
|
}
|
|
|
|
private void Execute(JobState state, CancellationToken stoppingToken)
|
|
{
|
|
JobSnapshot snapshot;
|
|
lock (state.Sync)
|
|
{
|
|
state.Status = JobStatus.Running;
|
|
state.StartedAt = DateTime.Now;
|
|
state.Stage = "Starting";
|
|
state.Sequence++;
|
|
snapshot = state.ToSnapshot();
|
|
}
|
|
_ = _publisher.JobChangedAsync(snapshot);
|
|
|
|
TimeSpan throttle = TimeSpan.FromMilliseconds(Math.Max(50, _settings.ProgressThrottleMilliseconds));
|
|
using (JobProgressReporter reporter = new JobProgressReporter(state, _publisher, throttle, stoppingToken))
|
|
{
|
|
object result = null;
|
|
Exception failure = null;
|
|
try
|
|
{
|
|
result = state.Request.Work(reporter);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
failure = ex;
|
|
ExceptionLog.Write(ex);
|
|
}
|
|
|
|
reporter.Dispose(); // no late throttled message may arrive after the final one
|
|
|
|
lock (state.Sync)
|
|
{
|
|
state.FinishedAt = DateTime.Now;
|
|
if (failure == null)
|
|
{
|
|
state.Status = JobStatus.Succeeded;
|
|
state.Percent = 100;
|
|
state.Stage = "Completed";
|
|
state.Detail = null;
|
|
state.Result = result;
|
|
}
|
|
else
|
|
{
|
|
state.Status = JobStatus.Failed;
|
|
state.Error = UserMessage(failure);
|
|
}
|
|
state.Sequence++;
|
|
snapshot = state.ToSnapshot();
|
|
}
|
|
}
|
|
|
|
_store.Finished(state);
|
|
_ = _publisher.JobChangedAsync(snapshot);
|
|
}
|
|
|
|
/// <summary>The message the user should read: services wrap the real error in ServiceException with the same text.</summary>
|
|
private static string UserMessage(Exception ex)
|
|
{
|
|
Exception e = ex;
|
|
while (e is AggregateException && e.InnerException != null)
|
|
e = e.InnerException;
|
|
return string.IsNullOrWhiteSpace(e.Message) ? "The job failed." : e.Message;
|
|
}
|
|
}
|
|
}
|