-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpubsub.go
208 lines (171 loc) · 4.78 KB
/
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
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
package interfaces
import (
"context"
"encoding/json"
"errors"
"os"
"strings"
"cloud.google.com/go/pubsub"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/wwwillw/pixelland-chat/graph/model"
pixellandchat "github.com/wwwillw/pixelland-chat/pixellandchat"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
)
var pubsubClient *PubsubClient
type PubsubConfig struct {
ServiceAccountPath string
AuthorEventsTopic string
InstanceEventsTopic string
UserEventsTopic string
Active bool
IsProd bool
PubsubProjectId string
}
type PubsubClient struct {
client *pubsub.Client
config PubsubConfig
}
type PubsubData struct {
Token string
Payload []byte
}
func InitPubSubClient(ctx context.Context, config PubsubConfig) error {
pubsubClient = &PubsubClient{
client: nil,
config: config,
}
if !config.Active {
log.Info().Msg("Pubsub client is not active")
return nil
}
projectId := config.PubsubProjectId
if projectId == "" {
var credentials *google.Credentials
if _, err := os.Stat(config.ServiceAccountPath); err == nil {
bytes, err := os.ReadFile(config.ServiceAccountPath)
if err != nil {
return err
}
credentials, err = google.CredentialsFromJSON(ctx, bytes, compute.ComputeScope)
if err != nil {
return err
}
} else if errors.Is(err, os.ErrNotExist) {
credentials, err = google.FindDefaultCredentials(ctx, compute.ComputeScope)
if err != nil {
return err
}
} else {
return err
}
projectId = credentials.ProjectID
}
log.Info().Msgf("Initializing pubsub client for project %s", projectId)
client, err := pubsub.NewClient(ctx, projectId)
if err != nil {
return err
}
pubsubClient.client = client
return nil
}
func GetPubSubClient() *PubsubClient {
return pubsubClient
}
func (c *PubsubClient) PublishUserEvent(ctx context.Context, kind model.NoticeKind, user pixellandchat.UserFragment) error {
if !c.config.Active {
log.Info().Msg("Not publishing user event because pubsub client is not active")
return nil
}
kindStr := string(kind)
if !strings.Contains(kindStr, "USER") {
return errors.New("Invalid notice kind, must be a user notice")
}
return c.publishPubsubEvent(ctx, kindStr, uuid.Nil, user)
}
func (c *PubsubClient) PublishAuthorEvent(ctx context.Context, kind model.NoticeKind, author pixellandchat.AuthorFragment) error {
if !c.config.Active {
log.Info().Msg("Not publishing author event because pubsub client is not active")
return nil
}
kindStr := string(kind)
if !strings.Contains(kindStr, "AUTHOR") {
msg := "Invalid mutation type, must be author mutation"
log.Error().Msg(msg)
return errors.New(msg)
}
return c.publishPubsubEvent(ctx, kindStr, author.InstanceId, author)
}
func (c *PubsubClient) PublishInstanceEvent(ctx context.Context, kind model.NoticeKind, instance pixellandchat.InstanceFragment) error {
if !c.config.Active {
log.Info().Msg("Not publishing instance event because pubsub client is not active")
return nil
}
kindStr := string(kind)
if !strings.Contains(kindStr, "INSTANCE") {
return errors.New("Invalid mutation type, must be instance mutation")
}
return c.publishPubsubEvent(ctx, kindStr, instance.Id, instance)
}
func (c *PubsubClient) publishPubsubEvent(ctx context.Context, kind string, instanceID uuid.UUID, model interface{}) error {
kindStr := string(kind)
var topicName string
if strings.Contains(kindStr, "INSTANCE") {
topicName = c.config.InstanceEventsTopic
} else if strings.Contains(kindStr, "AUTHOR") {
topicName = c.config.AuthorEventsTopic
} else if strings.Contains(kindStr, "USER") {
topicName = c.config.UserEventsTopic
} else {
return errors.New("Invalid mutation type")
}
topic, err := getTopic(ctx, c.client, topicName, !c.config.IsProd)
if err != nil {
return err
}
payloadBytes, err := json.Marshal(model)
if err != nil {
return err
}
pubsubData := PubsubData{
Token: ctx.Value("token").(string),
Payload: payloadBytes,
}
dataBytes, err := json.Marshal(pubsubData)
if err != nil {
return err
}
log.Info().Msgf("Publishing pubsub event: %s", instanceID.String())
res := topic.Publish(ctx, &pubsub.Message{
Data: dataBytes,
Attributes: map[string]string{
"instanceId": instanceID.String(),
"mutationType": kindStr,
},
})
_, err = res.Get(ctx)
if err != nil {
return err
}
return nil
}
func getTopic(ctx context.Context, client *pubsub.Client, name string, createIfNotExists bool) (*pubsub.Topic, error) {
topic := client.Topic(name)
if createIfNotExists {
ok, err := topic.Exists(ctx)
if err != nil {
log.Err(err)
return nil, err
}
if ok {
return topic, nil
}
topic, err = client.CreateTopic(ctx, name)
if err != nil {
log.Err(err).Msg("Failed to create the topic")
return nil, err
}
}
return topic, nil
}