| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Elsa.Mediator.Contracts; |
| | | 3 | | using Elsa.Mediator.Models; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Mediator.Services; |
| | | 7 | | |
| | | 8 | | /// <inheritdoc /> |
| | 1 | 9 | | public class JobQueue(IJobsChannel jobsChannel, ILogger<JobQueue> logger) : IJobQueue |
| | | 10 | | { |
| | 1 | 11 | | private readonly ConcurrentDictionary<string, EnqueuedJob> _scheduledItems = new(); |
| | 1 | 12 | | private readonly ConcurrentDictionary<string, EnqueuedJob> _pendingItems = new(); |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public string Create(Func<CancellationToken, Task> job) |
| | | 16 | | { |
| | 0 | 17 | | var jobItem = CreateJob(job); |
| | 0 | 18 | | _pendingItems.TryAdd(jobItem.JobId, jobItem); |
| | 0 | 19 | | return jobItem.JobId; |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | public void Enqueue(string jobId) |
| | | 23 | | { |
| | 0 | 24 | | if (!_pendingItems.TryRemove(jobId, out var jobItem)) |
| | | 25 | | { |
| | 0 | 26 | | logger.LogWarning($"Job {jobId} was not found"); |
| | 0 | 27 | | return; |
| | | 28 | | } |
| | | 29 | | |
| | 0 | 30 | | _scheduledItems.TryAdd(jobItem.JobId, jobItem); |
| | 0 | 31 | | jobsChannel.Writer.TryWrite(jobItem); |
| | 0 | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <inheritdoc /> |
| | | 35 | | public string Enqueue(Func<CancellationToken, Task> job) |
| | | 36 | | { |
| | 0 | 37 | | var jobItem = CreateJob(job); |
| | 0 | 38 | | _scheduledItems.TryAdd(jobItem.JobId, jobItem); |
| | 0 | 39 | | jobsChannel.Writer.TryWrite(jobItem); |
| | 0 | 40 | | return jobItem.JobId; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <inheritdoc /> |
| | | 44 | | public bool Dequeue(string jobId) |
| | | 45 | | { |
| | 0 | 46 | | if (!_pendingItems.TryRemove(jobId, out _)) |
| | 0 | 47 | | if (!_scheduledItems.TryRemove(jobId, out _)) |
| | 0 | 48 | | return false; |
| | | 49 | | |
| | 0 | 50 | | return true; |
| | | 51 | | } |
| | | 52 | | |
| | | 53 | | /// <inheritdoc /> |
| | | 54 | | public bool Cancel(string jobId) |
| | | 55 | | { |
| | 0 | 56 | | if (!_pendingItems.TryGetValue(jobId, out var jobItem)) |
| | 0 | 57 | | if (!_scheduledItems.TryGetValue(jobId, out jobItem)) |
| | 0 | 58 | | return false; |
| | | 59 | | |
| | 0 | 60 | | jobItem.CancellationTokenSource.Cancel(); |
| | 0 | 61 | | return true; |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | private EnqueuedJob CreateJob(Func<CancellationToken, Task> job) |
| | | 65 | | { |
| | 0 | 66 | | var jobId = Guid.NewGuid().ToString(); |
| | 0 | 67 | | var cts = new CancellationTokenSource(); |
| | 0 | 68 | | return new EnqueuedJob(jobId, job, cts, OnJobCompleted); |
| | | 69 | | } |
| | | 70 | | |
| | 0 | 71 | | void OnJobCompleted(string completedJobId) => _scheduledItems.TryRemove(completedJobId, out _); |
| | | 72 | | } |