-
Notifications
You must be signed in to change notification settings - Fork 3
/
task_worker.go
184 lines (160 loc) · 5.25 KB
/
task_worker.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
package task
import (
"context"
"github.com/data-preservation-programs/RetrievalBot/pkg/env"
"github.com/google/uuid"
logging "github.com/ipfs/go-log/v2"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"strings"
"time"
)
type Worker interface {
DoWork(task Task) (*RetrievalResult, error)
}
type WorkerProcess struct {
id uuid.UUID
taskCollection *mongo.Collection
resultCollection *mongo.Collection
worker Worker
module ModuleName
acceptedContinents string
acceptedCountries string
pollInterval time.Duration
retrieverInfo Retriever
timeoutBuffer time.Duration
}
func (t WorkerProcess) Close() {
// nolint:errcheck
t.taskCollection.Database().Client().Disconnect(context.Background())
// nolint:errcheck
t.resultCollection.Database().Client().Disconnect(context.Background())
}
func NewTaskWorkerProcess(
ctx context.Context,
module ModuleName,
worker Worker) (*WorkerProcess, error) {
taskClient, err := mongo.Connect(ctx, options.Client().ApplyURI(env.GetRequiredString(env.QueueMongoURI)))
if err != nil {
return nil, errors.Wrap(err, "failed to connect to mongo queueDB")
}
taskCollection := taskClient.Database(env.GetRequiredString(env.QueueMongoDatabase)).Collection("task_queue")
resultClient, err := mongo.Connect(ctx, options.Client().ApplyURI(env.GetRequiredString(env.ResultMongoURI)))
if err != nil {
return nil, errors.Wrap(err, "failed to connect to mongo resultDB")
}
resultCollection := resultClient.Database(env.GetRequiredString(env.ResultMongoDatabase)).Collection("task_result")
retrieverInfo := Retriever{
PublicIP: env.GetRequiredString(env.PublicIP),
City: env.GetRequiredString(env.City),
Region: env.GetRequiredString(env.Region),
Country: env.GetRequiredString(env.Country),
Continent: env.GetRequiredString(env.Continent),
ASN: env.GetRequiredString(env.ASN),
ISP: env.GetRequiredString(env.ISP),
Latitude: env.GetRequiredFloat32(env.Latitude),
Longitude: env.GetRequiredFloat32(env.Longitude),
}
id := uuid.New()
return &WorkerProcess{
id,
taskCollection,
resultCollection,
worker,
module,
env.GetString(env.AcceptedContinents, ""),
env.GetString(env.AcceptedCountries, ""),
env.GetDuration(env.TaskWorkerPollInterval, 10*time.Second),
retrieverInfo,
env.GetDuration(env.TaskWorkerTimeoutBuffer, 10*time.Second),
}, nil
}
func (t WorkerProcess) Poll(ctx context.Context) error {
logger := logging.Logger("task-worker").With("protocol", t.module, "workerId", t.id)
var singleResult *mongo.SingleResult
for {
logger.Debug("polling for task")
//nolint:govet
match := bson.D{
{"module", t.module},
}
if len(t.acceptedCountries) > 0 {
if strings.HasPrefix(t.acceptedCountries, "!") {
match = append(match, bson.E{Key: "provider.country",
Value: bson.D{{Key: "$nin", Value: strings.Split(t.acceptedCountries[1:], ",")}}})
} else {
match = append(match, bson.E{Key: "provider.country",
Value: bson.D{{Key: "$in", Value: strings.Split(t.acceptedCountries, ",")}}})
}
}
if len(t.acceptedContinents) > 0 {
if strings.HasPrefix(t.acceptedContinents, "!") {
match = append(match, bson.E{Key: "provider.continent",
Value: bson.D{{Key: "$nin", Value: strings.Split(t.acceptedContinents[1:], ",")}}})
} else {
match = append(match, bson.E{Key: "provider.continent",
Value: bson.D{{Key: "$in", Value: strings.Split(t.acceptedContinents, ",")}}})
}
}
logger.With("filter", match).Debug("FindOneAndDelete")
singleResult = t.taskCollection.FindOneAndDelete(ctx, match,
options.FindOneAndDelete().SetSort(bson.D{{Key: "created_at", Value: 1}}))
if errors.Is(singleResult.Err(), mongo.ErrNoDocuments) {
logger.Debug("no task singleResult")
time.Sleep(t.pollInterval)
continue
}
if singleResult.Err() != nil {
return errors.Wrap(singleResult.Err(), "failed to find task")
}
break
}
found := new(Task)
err := singleResult.Decode(found)
if err != nil {
return errors.Wrap(err, "failed to decode task")
}
logger.With("task", found).Info("found new task")
resultChan := make(chan RetrievalResult)
errChan := make(chan error)
go func() {
result, err := t.worker.DoWork(*found)
if err != nil {
errResult := resolveErrorResult(err)
if errResult != nil {
resultChan <- *errResult
} else {
logger.With("error", err).Error("failed to do work")
errChan <- err
}
} else {
resultChan <- *result
}
}()
var retrievalResult RetrievalResult
select {
case <-ctx.Done():
//nolint:wrapcheck
return ctx.Err()
case <-time.After(found.Timeout + t.timeoutBuffer):
retrievalResult = *NewErrorRetrievalResult(Timeout, errors.Errorf("timed out after %s", found.Timeout))
case r := <-resultChan:
retrievalResult = r
case err = <-errChan:
return err
}
taskResult := Result{
Task: *found,
Result: retrievalResult,
Retriever: t.retrieverInfo,
CreatedAt: time.Now().UTC(),
}
insertResult, err := t.resultCollection.InsertOne(ctx, taskResult)
if err != nil {
return errors.Wrap(err, "failed to insert result")
}
logger.With("result", retrievalResult, "InsertedID", insertResult.InsertedID).Info("inserted result")
return nil
}