forked from riverqueue/river
-
Notifications
You must be signed in to change notification settings - Fork 0
/
job_list_params.go
287 lines (256 loc) · 7.82 KB
/
job_list_params.go
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package river
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"weavelab.xyz/river/internal/dbadapter"
"weavelab.xyz/river/rivertype"
)
// JobListCursor is used to specify a starting point for a paginated
// job list query.
type JobListCursor struct {
id int64
kind string
queue string
time time.Time
}
// JobListCursorFromJob creates a JobListCursor from a JobRow.
func JobListCursorFromJob(job *rivertype.JobRow) *JobListCursor {
return &JobListCursor{
id: job.ID,
kind: job.Kind,
queue: job.Queue,
time: jobListTimeValue(job),
}
}
// UnmarshalText implements encoding.TextUnmarshaler to decode the cursor from
// a previously marshaled string.
func (c *JobListCursor) UnmarshalText(text []byte) error {
dst := make([]byte, base64.StdEncoding.DecodedLen(len(text)))
n, err := base64.StdEncoding.Decode(dst, text)
if err != nil {
return err
}
dst = dst[:n]
wrapperValue := jobListPaginationCursorJSON{}
if err := json.Unmarshal(dst, &wrapperValue); err != nil {
return err
}
*c = JobListCursor{
id: wrapperValue.ID,
kind: wrapperValue.Kind,
queue: wrapperValue.Queue,
time: wrapperValue.Time,
}
return nil
}
// MarshalText implements encoding.TextMarshaler to encode the cursor as an
// opaque string.
func (c JobListCursor) MarshalText() ([]byte, error) {
wrapperValue := jobListPaginationCursorJSON{
ID: c.id,
Kind: c.kind,
Queue: c.queue,
Time: c.time,
}
data, err := json.Marshal(wrapperValue)
if err != nil {
return nil, err
}
dst := make([]byte, base64.URLEncoding.EncodedLen(len(data)))
base64.URLEncoding.Encode(dst, data)
return dst, nil
}
type jobListPaginationCursorJSON struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Queue string `json:"queue"`
Time time.Time `json:"time"`
}
// SortOrder specifies the direction of a sort.
type SortOrder int
const (
// SortOrderAsc specifies that the sort should in ascending order.
SortOrderAsc SortOrder = iota
// SortOrderDesc specifies that the sort should in descending order.
SortOrderDesc
)
// JobListOrderByField specifies the field to sort by.
type JobListOrderByField int
const (
// JobListOrderByTime specifies that the sort should be by time. The specific
// time field used will vary by job state.
JobListOrderByTime JobListOrderByField = iota
)
// JobListParams specifies the parameters for a JobList query. It must be
// initialized with NewJobListParams. Params can be built by chaining methods on
// the JobListParams object:
//
// params := NewJobListParams().OrderBy(JobListOrderByTime, SortOrderAsc).First(100)
type JobListParams struct {
after *JobListCursor
metadataFragment string
paginationCount int32
queues []string
sortField JobListOrderByField
sortOrder SortOrder
state rivertype.JobState
}
// NewJobListParams creates a new JobListParams to return available jobs sorted
// by time in ascending order, returning 100 jobs at most.
func NewJobListParams() *JobListParams {
return &JobListParams{
paginationCount: 100,
sortField: JobListOrderByTime,
sortOrder: SortOrderAsc,
state: rivertype.JobStateAvailable,
}
}
func (p *JobListParams) copy() *JobListParams {
return &JobListParams{
after: p.after,
metadataFragment: p.metadataFragment,
paginationCount: p.paginationCount,
queues: append([]string(nil), p.queues...),
sortField: p.sortField,
sortOrder: p.sortOrder,
state: p.state,
}
}
func (p *JobListParams) toDBParams() (*dbadapter.JobListParams, error) {
conditionsBuilder := &strings.Builder{}
conditions := make([]string, 0, 10)
namedArgs := make(map[string]any)
orderBy := []dbadapter.JobListOrderBy{}
var sortOrder dbadapter.SortOrder
switch p.sortOrder {
case SortOrderAsc:
sortOrder = dbadapter.SortOrderAsc
case SortOrderDesc:
sortOrder = dbadapter.SortOrderDesc
default:
return nil, errors.New("invalid sort order")
}
if p.sortField != JobListOrderByTime {
return nil, errors.New("invalid sort field")
}
timeField := jobListTimeFieldForState(p.state)
orderBy = append(orderBy, []dbadapter.JobListOrderBy{
{Expr: timeField, Order: sortOrder},
{Expr: "id", Order: sortOrder},
}...)
if p.metadataFragment != "" {
conditions = append(conditions, `metadata @> @metadata_fragment::jsonb`)
namedArgs["metadata_fragment"] = p.metadataFragment
}
if p.after != nil {
if sortOrder == dbadapter.SortOrderAsc {
conditions = append(conditions, fmt.Sprintf(`("%s" > @cursor_time OR ("%s" = @cursor_time AND "id" > @after_id))`, timeField, timeField))
} else {
conditions = append(conditions, fmt.Sprintf(`("%s" < @cursor_time OR ("%s" = @cursor_time AND "id" < @after_id))`, timeField, timeField))
}
namedArgs["cursor_time"] = p.after.time
namedArgs["after_id"] = p.after.id
}
for i, condition := range conditions {
if i > 0 {
conditionsBuilder.WriteString("\n AND ")
}
conditionsBuilder.WriteString(condition)
}
dbParams := &dbadapter.JobListParams{
Conditions: conditionsBuilder.String(),
LimitCount: p.paginationCount,
NamedArgs: namedArgs,
OrderBy: orderBy,
Priorities: nil,
Queues: p.queues,
State: p.state,
}
return dbParams, nil
}
// After returns an updated filter set that will only return jobs
// after the given cursor.
func (p *JobListParams) After(cursor *JobListCursor) *JobListParams {
result := p.copy()
result.after = cursor
return result
}
// First returns an updated filter set that will only return the first
// count jobs.
//
// Count must be between 1 and 10000, inclusive, or this will panic.
func (p *JobListParams) First(count int) *JobListParams {
if count <= 0 {
panic("count must be > 0")
}
if count > 10000 {
panic("count must be <= 10000")
}
result := p.copy()
result.paginationCount = int32(count)
return result
}
func (p *JobListParams) Metadata(json string) *JobListParams {
result := p.copy()
result.metadataFragment = json
return result
}
// Queues returns an updated filter set that will only return jobs from the
// given queues.
func (p *JobListParams) Queues(queues ...string) *JobListParams {
result := p.copy()
result.queues = make([]string, 0, len(queues))
copy(result.queues, queues)
return result
}
// OrderBy returns an updated filter set that will sort the results using the
// specified field and direction.
func (p *JobListParams) OrderBy(field JobListOrderByField, direction SortOrder) *JobListParams {
result := p.copy()
result.sortField = field
result.sortOrder = direction
return result
}
// State returns an updated filter set that will only return jobs in the given
// state.
func (p *JobListParams) State(state rivertype.JobState) *JobListParams {
result := p.copy()
result.state = state
return result
}
func jobListTimeFieldForState(state rivertype.JobState) string {
switch state {
case rivertype.JobStateAvailable, rivertype.JobStateRetryable, rivertype.JobStateScheduled:
return "scheduled_at"
case rivertype.JobStateRunning:
return "attempted_at"
case rivertype.JobStateCancelled, rivertype.JobStateCompleted, rivertype.JobStateDiscarded:
return "finalized_at"
default:
return "created_at" // should never happen
}
}
func jobListTimeValue(job *rivertype.JobRow) time.Time {
switch job.State {
case rivertype.JobStateAvailable, rivertype.JobStateRetryable, rivertype.JobStateScheduled:
return job.ScheduledAt
case rivertype.JobStateRunning:
if job.AttemptedAt == nil {
// This should never happen unless a job has been manually manipulated.
return job.CreatedAt
}
return *job.AttemptedAt
case rivertype.JobStateCancelled, rivertype.JobStateCompleted, rivertype.JobStateDiscarded:
if job.FinalizedAt == nil {
// This should never happen unless a job has been manually manipulated.
return job.CreatedAt
}
return *job.FinalizedAt
default:
return job.CreatedAt // should never happen
}
}