forked from openflagr/flagr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_recorder_pubsub.go
72 lines (64 loc) · 1.84 KB
/
data_recorder_pubsub.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
package handler
import (
"context"
"cloud.google.com/go/pubsub"
"github.com/paubox/paubox-flagr/pkg/config"
"github.com/paubox/paubox-flagr/swagger_gen/models"
"github.com/sirupsen/logrus"
"google.golang.org/api/option"
)
type pubsubRecorder struct {
producer *pubsub.Client
topic *pubsub.Topic
options DataRecordFrameOptions
}
var (
pubsubClient = func() (*pubsub.Client, error) {
return pubsub.NewClient(
context.Background(),
config.Config.RecorderPubsubProjectID,
option.WithCredentialsFile(config.Config.RecorderPubsubKeyFile),
)
}
)
// NewPubsubRecorder creates a new Pubsub recorder
var NewPubsubRecorder = func() DataRecorder {
client, err := pubsubClient()
if err != nil {
logrus.WithField("pubsub_error", err).Fatal("error getting pubsub client")
}
return &pubsubRecorder{
producer: client,
topic: client.Topic(config.Config.RecorderPubsubTopicName),
options: DataRecordFrameOptions{
Encrypted: false, // not implemented yet
FrameOutputMode: config.Config.RecorderFrameOutputMode,
},
}
}
func (p *pubsubRecorder) NewDataRecordFrame(r models.EvalResult) DataRecordFrame {
return DataRecordFrame{
evalResult: r,
options: p.options,
}
}
func (p *pubsubRecorder) AsyncRecord(r models.EvalResult) {
frame := p.NewDataRecordFrame(r)
output, err := frame.Output()
if err != nil {
logrus.WithField("err", err).Error("failed to generate data record frame for pubsub recorder")
return
}
ctx := context.Background()
res := p.topic.Publish(ctx, &pubsub.Message{Data: output})
if config.Config.RecorderPubsubVerbose {
go func() {
ctx, cancel := context.WithTimeout(ctx, config.Config.RecorderPubsubVerboseCancelTimeout)
defer cancel()
id, err := res.Get(ctx)
if err != nil {
logrus.WithFields(logrus.Fields{"pubsub_error": err, "id": id}).Error("error pushing to pubsub")
}
}()
}
}