-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonJobQueue.cs
More file actions
194 lines (162 loc) · 7.63 KB
/
JsonJobQueue.cs
File metadata and controls
194 lines (162 loc) · 7.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Birko.BackgroundJobs.JSON.Models;
using Birko.Data.JSON.Stores;
using Birko.Data.Stores;
using Birko.Configuration;
using Birko.Time;
namespace Birko.BackgroundJobs.JSON
{
/// <summary>
/// JSON file-based job queue using Birko.Data.JSON stores.
/// Good for development, testing, and single-process deployments.
/// </summary>
public class JsonJobQueue : IJobQueue
{
private readonly AsyncJsonStore<JsonJobDescriptorModel> _store;
private readonly RetryPolicy _retryPolicy;
private readonly IDateTimeProvider _clock;
/// <summary>
/// Creates a new JSON job queue.
/// </summary>
public JsonJobQueue(Birko.Configuration.Settings settings, IDateTimeProvider clock, RetryPolicy? retryPolicy = null)
{
_store = new AsyncJsonStore<JsonJobDescriptorModel>();
_store.SetSettings(settings);
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_retryPolicy = retryPolicy ?? RetryPolicy.Default;
}
/// <summary>
/// Creates a new JSON job queue from an existing store.
/// </summary>
public JsonJobQueue(AsyncJsonStore<JsonJobDescriptorModel> store, IDateTimeProvider clock, RetryPolicy? retryPolicy = null)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_retryPolicy = retryPolicy ?? RetryPolicy.Default;
}
/// <summary>
/// Gets the underlying store for advanced scenarios.
/// </summary>
public AsyncJsonStore<JsonJobDescriptorModel> Store => _store;
public async Task<Guid> EnqueueAsync(JobDescriptor descriptor, CancellationToken cancellationToken = default)
{
var model = JsonJobDescriptorModel.FromDescriptor(descriptor);
var id = await _store.CreateAsync(model, ct: cancellationToken).ConfigureAwait(false);
return id;
}
public async Task<JobDescriptor?> DequeueAsync(string? queueName = null, CancellationToken cancellationToken = default)
{
var now = _clock.UtcNow;
var pendingStatus = (int)JobStatus.Pending;
var scheduledStatus = (int)JobStatus.Scheduled;
IEnumerable<JsonJobDescriptorModel> candidates;
if (queueName != null)
{
candidates = await _store.ReadAsync(
filter: j => (j.Status == pendingStatus || (j.Status == scheduledStatus && j.ScheduledAt != null && j.ScheduledAt <= now))
&& (j.QueueName == null || j.QueueName == queueName),
orderBy: OrderBy<JsonJobDescriptorModel>.ByDescending(j => j.Priority).ThenBy(j => j.EnqueuedAt),
limit: 1,
ct: cancellationToken
).ConfigureAwait(false);
}
else
{
candidates = await _store.ReadAsync(
filter: j => j.Status == pendingStatus || (j.Status == scheduledStatus && j.ScheduledAt != null && j.ScheduledAt <= now),
orderBy: OrderBy<JsonJobDescriptorModel>.ByDescending(j => j.Priority).ThenBy(j => j.EnqueuedAt),
limit: 1,
ct: cancellationToken
).ConfigureAwait(false);
}
var candidate = candidates.FirstOrDefault();
if (candidate == null)
{
return null;
}
candidate.Status = (int)JobStatus.Processing;
candidate.AttemptCount++;
candidate.LastAttemptAt = _clock.UtcNow;
await _store.UpdateAsync(candidate, ct: cancellationToken).ConfigureAwait(false);
return candidate.ToDescriptor();
}
public async Task CompleteAsync(Guid jobId, CancellationToken cancellationToken = default)
{
var model = await _store.ReadAsync(j => j.Guid == jobId, cancellationToken).ConfigureAwait(false);
if (model == null) return;
model.Status = (int)JobStatus.Completed;
model.CompletedAt = _clock.UtcNow;
await _store.UpdateAsync(model, ct: cancellationToken).ConfigureAwait(false);
}
public async Task FailAsync(Guid jobId, string error, CancellationToken cancellationToken = default)
{
var model = await _store.ReadAsync(j => j.Guid == jobId, cancellationToken).ConfigureAwait(false);
if (model == null) return;
model.LastError = error;
if (model.AttemptCount < model.MaxRetries)
{
var delay = _retryPolicy.GetDelay(model.AttemptCount);
model.Status = (int)JobStatus.Scheduled;
model.ScheduledAt = _clock.UtcNow.Add(delay);
}
else
{
model.Status = (int)JobStatus.Dead;
model.CompletedAt = _clock.UtcNow;
}
await _store.UpdateAsync(model, ct: cancellationToken).ConfigureAwait(false);
}
public async Task<bool> CancelAsync(Guid jobId, CancellationToken cancellationToken = default)
{
var pendingStatus = (int)JobStatus.Pending;
var scheduledStatus = (int)JobStatus.Scheduled;
var model = await _store.ReadAsync(
j => j.Guid == jobId && (j.Status == pendingStatus || j.Status == scheduledStatus),
cancellationToken
).ConfigureAwait(false);
if (model == null) return false;
model.Status = (int)JobStatus.Cancelled;
model.CompletedAt = _clock.UtcNow;
await _store.UpdateAsync(model, ct: cancellationToken).ConfigureAwait(false);
return true;
}
public async Task<JobDescriptor?> GetAsync(Guid jobId, CancellationToken cancellationToken = default)
{
var model = await _store.ReadAsync(j => j.Guid == jobId, cancellationToken).ConfigureAwait(false);
return model?.ToDescriptor();
}
public async Task<IReadOnlyList<JobDescriptor>> GetByStatusAsync(JobStatus status, int limit = 100, CancellationToken cancellationToken = default)
{
var statusInt = (int)status;
var models = await _store.ReadAsync(
filter: j => j.Status == statusInt,
orderBy: OrderBy<JsonJobDescriptorModel>.ByDescending(j => j.EnqueuedAt),
limit: limit,
ct: cancellationToken
).ConfigureAwait(false);
return models.Select(m => m.ToDescriptor()).ToList();
}
public async Task<int> PurgeAsync(TimeSpan olderThan, CancellationToken cancellationToken = default)
{
var cutoff = _clock.UtcNow.Subtract(olderThan);
var completedStatus = (int)JobStatus.Completed;
var deadStatus = (int)JobStatus.Dead;
var cancelledStatus = (int)JobStatus.Cancelled;
var toPurge = await _store.ReadAsync(
filter: j => (j.Status == completedStatus || j.Status == deadStatus || j.Status == cancelledStatus)
&& j.CompletedAt != null && j.CompletedAt < cutoff,
ct: cancellationToken
).ConfigureAwait(false);
var list = toPurge.ToList();
if (list.Count > 0)
{
await _store.DeleteAsync(list, cancellationToken).ConfigureAwait(false);
}
return list.Count;
}
}
}