-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathclient.go
More file actions
276 lines (221 loc) · 6.69 KB
/
client.go
File metadata and controls
276 lines (221 loc) · 6.69 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
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
package backlite
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"sync"
"time"
"github.com/mikestefanello/backlite/internal/query"
"github.com/mikestefanello/backlite/internal/task"
)
// now returns the current time in a way that tests can override.
var now = func() time.Time { return time.Now() }
type (
// Client is a client used to register queues and add tasks to them for execution.
Client struct {
// db stores the database to use for storing tasks.
db *sql.DB
// log is the logger.
log Logger
// queues stores the registered queues which tasks can be added to.
queues queues
// buffers is a pool of byte buffers for more efficient encoding.
buffers sync.Pool
// dispatcher is used to fetch and dispatch queued tasks to the workers for execution.
dispatcher Dispatcher
}
// ClientConfig contains configuration for the Client.
ClientConfig struct {
// DB is the open database connection used for storing tasks.
DB *sql.DB
// Logger is the logger used to log task execution.
Logger Logger
// NumWorkers is the number of goroutines to open to use for executing queued tasks concurrently.
NumWorkers int
// ReleaseAfter is the duration after which a task is released back to a queue if it has not finished executing.
// This value should be much higher than the timeout setting used for each queue and exists as a fail-safe
// just in case tasks become stuck.
ReleaseAfter time.Duration
// CleanupInterval is how often to run cleanup operations on the database in order to remove expired completed
// tasks. If omitted, no cleanup operations will be performed and the task retention duration will be ignored.
CleanupInterval time.Duration
}
// ctxKeyClient is used to store a Client in a context.
ctxKeyClient struct{}
TaskStatus int
)
const (
// TaskStatusPending indicates the task is awaiting execution.
TaskStatusPending TaskStatus = iota
// TaskStatusRunning indicates the task is being executed.
TaskStatusRunning
// TaskStatusSuccess indicates the task completed successfully.
TaskStatusSuccess
// TaskStatusFailure indicates the task execution failed.
TaskStatusFailure
// TaskStatusNotFound indicates the task was not found in the database.
TaskStatusNotFound
)
// FromContext returns a Client from a context which is set for queue processor callbacks, so they can access
// the client in order to create additional tasks.
func FromContext(ctx context.Context) *Client {
if c, ok := ctx.Value(ctxKeyClient{}).(*Client); ok {
return c
}
return nil
}
// NewClient initializes a new Client
func NewClient(cfg ClientConfig) (*Client, error) {
switch {
case cfg.DB == nil:
return nil, errors.New("missing database")
case cfg.NumWorkers < 1:
return nil, errors.New("at least one worker required")
case cfg.ReleaseAfter <= 0:
return nil, errors.New("release duration must be greater than zero")
}
if cfg.Logger == nil {
cfg.Logger = &noLogger{}
}
c := &Client{
db: cfg.DB,
log: cfg.Logger,
queues: queues{registry: make(map[string]Queue)},
buffers: sync.Pool{
New: func() any {
return bytes.NewBuffer(nil)
},
},
}
c.dispatcher = &dispatcher{
client: c,
log: cfg.Logger,
numWorkers: cfg.NumWorkers,
releaseAfter: cfg.ReleaseAfter,
cleanupInterval: cfg.CleanupInterval,
}
return c, nil
}
// Register registers a new Queue so tasks can be added to it.
// This will panic if the name of the queue provided has already been registered.
func (c *Client) Register(queue Queue) {
c.queues.add(queue)
}
// Add starts an operation to add one or many tasks.
func (c *Client) Add(tasks ...Task) *TaskAddOp {
return &TaskAddOp{
client: c,
tasks: tasks,
}
}
// Start starts the dispatcher so queued tasks can automatically be executed in the background.
// To gracefully shut down the dispatcher, call Stop(), or to hard-stop, cancel the provided context.
func (c *Client) Start(ctx context.Context) {
c.dispatcher.Start(ctx)
}
// Stop attempts to gracefully shut down the dispatcher before the provided context is cancelled.
// True is returned if all workers were able to complete their tasks prior to shutting down.
func (c *Client) Stop(ctx context.Context) bool {
return c.dispatcher.Stop(ctx)
}
// Install installs the provided schema in the database.
// TODO provide migrations
func (c *Client) Install() error {
_, err := c.db.Exec(query.Schema)
return err
}
// Notify notifies the dispatcher that a new task has been added.
// This is only needed and required if you supply a database transaction when adding a task.
// See TaskAddOp.Tx().
func (c *Client) Notify() {
c.dispatcher.Notify()
}
// save saves a task add operation.
func (c *Client) save(op *TaskAddOp) ([]string, error) {
var commit bool
var err error
// Get a buffer for the encoding.
buf := c.buffers.Get().(*bytes.Buffer)
// Put the buffer back in the pool for re-use.
defer func() {
buf.Reset()
c.buffers.Put(buf)
}()
if op.ctx == nil {
op.ctx = context.Background()
}
// Start a transaction if one isn't provided.
if op.tx == nil {
op.tx, err = c.db.BeginTx(op.ctx, nil)
if err != nil {
return nil, err
}
commit = true
defer func() {
if err == nil {
return
}
if err = op.tx.Rollback(); err != nil {
c.log.Error("failed to rollback task creation transaction",
"error", err,
)
}
}()
}
// Collect the task IDs.
ids := make([]string, len(op.tasks))
// Insert the tasks.
for i, t := range op.tasks {
buf.Reset()
if err = json.NewEncoder(buf).Encode(t); err != nil {
return nil, err
}
m := task.Task{
Queue: t.Config().Name,
Task: buf.Bytes(),
WaitUntil: op.wait,
CreatedAt: now(),
}
if err = m.InsertTx(op.ctx, op.tx); err != nil {
return nil, err
}
ids[i] = m.ID
}
// If we created the transaction we'll commit it now.
if commit {
if err = op.tx.Commit(); err != nil {
return nil, err
}
// Tell the dispatcher that a new task has been added.
c.Notify()
}
return ids, nil
}
// Status returns the status of a task with a given ID.
// If the queue does not retain completed tasks, TaskStatusNotFound will be returned
// for completed tasks rather than TaskStatusSuccess or TaskStatusFailure.
func (c *Client) Status(ctx context.Context, taskID string) (TaskStatus, error) {
var running bool
var success *bool
err := c.db.QueryRowContext(ctx, query.SelectTaskStatus, taskID, taskID).
Scan(&running, &success)
switch err {
case nil:
case sql.ErrNoRows:
return TaskStatusNotFound, nil
default:
return 0, err
}
if success != nil {
if *success {
return TaskStatusSuccess, nil
}
return TaskStatusFailure, nil
}
if running {
return TaskStatusRunning, nil
}
return TaskStatusPending, nil
}