-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
66 lines (53 loc) · 1.23 KB
/
queue.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
package main
import (
"context"
"errors"
"fmt"
"cloud.google.com/go/pubsub"
)
// queue pushes events to pubsub topic
type queue struct {
client *pubsub.Client
topic *pubsub.Topic
}
// newQueue is invoked once per Storable life cycle to configure the store
func newQueue(ctx context.Context, projectID, topicName string) (q *queue, err error) {
logger.Print("Init Queue...")
if projectID == "" {
return nil, errors.New("projectID not set")
}
if topicName == "" {
return nil, errors.New("topicName not set")
}
if ctx == nil {
return nil, errors.New("context not set")
}
c, e := pubsub.NewClient(ctx, projectID)
if e != nil {
return nil, e
}
t := c.Topic(topicName)
topicExists, err := t.Exists(ctx)
if err != nil {
return nil, err
}
if !topicExists {
logger.Printf("Topic %s not found, creating...", topicName)
t, err = c.CreateTopic(ctx, topicName)
if err != nil {
return nil, fmt.Errorf("Unable to create topic: %s - %v", topicName, err)
}
}
o := &queue{
client: c,
topic: t,
}
return o, nil
}
// push persist the content
func (q *queue) push(ctx context.Context, data []byte) error {
msg := &pubsub.Message{Data: data}
result := q.topic.Publish(ctx, msg)
_, err := result.Get(ctx)
return err
}