-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpubsub.go
500 lines (404 loc) · 12.9 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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package raiden
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
"cloud.google.com/go/pubsub"
"github.com/oklog/run"
"github.com/sev-2/raiden/pkg/logger"
"github.com/sev-2/raiden/pkg/pubsub/google"
"github.com/valyala/fasthttp"
"go.opentelemetry.io/otel/trace"
"google.golang.org/api/option"
)
var PubSubLogger = logger.HcLog().Named("raiden.pubsub")
// ----- Type Definition -----
type PubSubProviderType string
const (
PubSubProviderGoogle PubSubProviderType = "google"
PubSubProviderUnknown PubSubProviderType = "unknown"
)
type SubscriptionType string
const (
SubscriptionTypePull SubscriptionType = "pull"
SubscriptionTypePush SubscriptionType = "push"
)
const SubscriptionPrefixEndpoint = "pubsub-endpoint"
type PushSubscriptionMessage struct {
Data string `json:"data"`
MessageId string `json:"message_id"`
Publish_time string `json:"publish_time"`
}
type PushSubscriptionData struct {
Message PushSubscriptionMessage `json:"message"`
Subscription string `json:"subscription"`
}
// ----- Subscription Context -----
type SubscriberContext interface {
Config() *Config
Span() trace.Span
SetSpan(span trace.Span)
}
type subscriberContext struct {
context.Context
cfg *Config
span trace.Span
}
func (ctx *subscriberContext) Config() *Config {
return ctx.cfg
}
func (ctx *subscriberContext) Span() trace.Span {
return ctx.span
}
func (ctx *subscriberContext) SetSpan(span trace.Span) {
ctx.span = span
}
// ----- Subscription Handler -----
type SubscriberHandler interface {
AutoAck() bool
Name() string
Consume(ctx SubscriberContext, message any) error
Provider() PubSubProviderType
PushEndpoint() string
Subscription() string
SubscriptionType() SubscriptionType
Topic() string
}
type SubscriberBase struct{}
func (s *SubscriberBase) AutoAck() bool {
return true
}
func (s *SubscriberBase) Name() string {
return "unknown"
}
func (s *SubscriberBase) Provider() PubSubProviderType {
return PubSubProviderUnknown
}
func (s *SubscriberBase) Subscription() string {
return ""
}
func (s *SubscriberBase) PushEndpoint() string {
return ""
}
func (s *SubscriberBase) Topic() string {
return ""
}
func (s *SubscriberBase) SubscriptionType() SubscriptionType {
return SubscriptionTypePull
}
func (s *SubscriberBase) Consume(ctx SubscriberContext, message any) error {
return fmt.Errorf("subscriber %s in not implemented", s.Name())
}
// ----- Subscription Server -----
type PubSub interface {
Register(handler SubscriberHandler)
Publish(ctx context.Context, provider PubSubProviderType, topic string, message []byte) error
Listen()
Serve(handle SubscriberHandler) (fasthttp.RequestHandler, error)
Handlers() []SubscriberHandler
}
func NewPubsub(config *Config, tracer trace.Tracer) PubSub {
return &PubSubManager{
config: config,
provider: pubSubProvider{
google: &GooglePubSubProvider{
Config: config,
Tracer: tracer,
},
},
}
}
type PubSubManager struct {
config *Config
handlers []SubscriberHandler
provider pubSubProvider
}
type pubSubProvider struct {
// all provider
google PubSubProvider
}
// Register implements Subscriber.
func (s *PubSubManager) Register(handler SubscriberHandler) {
s.handlers = append(s.handlers, handler)
}
func (s *PubSubManager) Handlers() []SubscriberHandler {
return s.handlers
}
func (s *PubSubManager) GetHandlerCount() int {
return len(s.handlers)
}
func (s *PubSubManager) SetConfig(cfg *Config) {
s.config = cfg
}
func (s *PubSubManager) SetProvider(providerType PubSubProviderType, provider PubSubProvider) {
switch providerType {
case PubSubProviderGoogle:
s.provider.google = provider
}
}
func (s *PubSubManager) Serve(handler SubscriberHandler) (fasthttp.RequestHandler, error) {
if handler.SubscriptionType() != SubscriptionTypePush {
return nil, fmt.Errorf("subscription %s is not push subscription", handler.Name())
}
if err := s.provider.google.CreateSubscription(handler); err != nil {
return nil, err
}
subscriptionSignature := fmt.Sprintf("projects/%s/subscriptions/%s", s.config.GoogleProjectId, handler.Subscription())
return func(ctx *fasthttp.RequestCtx) {
var subCtx = subscriberContext{
cfg: s.config, Context: context.Background(),
}
ctx.SetContentType("application/json")
// validate data
var data PushSubscriptionData
if err := json.Unmarshal(ctx.Request.Body(), &data); err != nil {
errMsg := "{\"message\":\"invalid json data\"}"
if _, writeErr := ctx.WriteString(errMsg); writeErr != nil {
PubSubLogger.Error(fmt.Sprintf("%s endpoint handler ctx.WriteString() error", handler.Name()), "message", writeErr)
}
return
}
if data.Subscription != subscriptionSignature {
ctx.SetStatusCode(fasthttp.StatusUnprocessableEntity)
errMsg := "{\"message\":\"subscription validation failed: received unexpected subscription name\"}"
if _, writeErr := ctx.WriteString(errMsg); writeErr != nil {
PubSubLogger.Error(fmt.Sprintf("%s endpoint handler ctx.WriteString() error", handler.Name()), "message", writeErr)
}
return
}
response := map[string]any{"message": "success handle"}
if err := handler.Consume(&subCtx, data.Message); err != nil {
ctx.SetStatusCode(http.StatusInternalServerError)
response["message"] = err.Error()
resByte, err := json.Marshal(response)
if err != nil {
errMsg := "{\"message\":\"invalid json data\"}"
if _, writeErr := ctx.WriteString(errMsg); writeErr != nil {
// Log the error if necessary
PubSubLogger.Error(fmt.Sprintf("%s endpoint handler ctx.WriteString() error", handler.Name()), "message", writeErr)
}
return
}
if _, err := ctx.Write(resByte); err != nil {
PubSubLogger.Error(fmt.Sprintf("%s endpoint handler ctx.Write() error", handler.Name()), "message", err)
}
return
}
resByte, err := json.Marshal(response)
if err != nil {
errMsg := "{\"message\":\"invalid json data\"}"
if _, writeErr := ctx.WriteString(errMsg); writeErr != nil {
// Log the error if necessary
PubSubLogger.Error(fmt.Sprintf("%s endpoint handler ctx.WriteString() error in last step", handler.Name()), "message", writeErr)
}
return
}
if _, err := ctx.Write(resByte); err != nil {
PubSubLogger.Error(fmt.Sprintf("%s endpoint handler ctx.Write() error ins last step", handler.Name()), "message", err)
}
}, nil
}
// StartListen implements Subscriber.
func (s *PubSubManager) Listen() {
var g run.Group
var googlePullHandlers []SubscriberHandler
for _, h := range s.handlers {
if h.Provider() == PubSubProviderGoogle && h.SubscriptionType() == SubscriptionTypePull {
googlePullHandlers = append(googlePullHandlers, h)
}
}
if len(googlePullHandlers) > 0 {
g.Add(func() error {
return s.provider.google.StartListen(googlePullHandlers)
}, func(err error) {
if err := s.provider.google.StopListen(); err != nil {
PubSubLogger.Error("failed stop listener", "message", err)
}
})
if err := g.Run(); err != nil {
PubSubLogger.Error("stop subscribe", "message", err)
}
}
}
func (s *PubSubManager) Publish(ctx context.Context, provider PubSubProviderType, topic string, message []byte) error {
switch provider {
case PubSubProviderGoogle:
return s.provider.google.Publish(ctx, topic, message)
}
return errors.New("unsupported pubsub provider")
}
// ----- Pub Sub Provider -----
type PubSubProvider interface {
Publish(ctx context.Context, topic string, message []byte) error
CreateSubscription(SubscriberHandler) error
StartListen(handler []SubscriberHandler) error
StopListen() error
}
type GooglePubSubProvider struct {
Config *Config
Client google.PubSubClient
Tracer trace.Tracer
}
func (s *GooglePubSubProvider) validate() error {
if s.Config.GoogleProjectId == "" {
return errors.New("env GOOGLE_PROJECT_ID is required")
}
if s.Config.GoogleSaPath == "" {
return errors.New("env GOOGLE_SA_PATH is required")
}
return nil
}
func (s *GooglePubSubProvider) createClient() error {
client, err := pubsub.NewClient(context.Background(), s.Config.GoogleProjectId, option.WithCredentialsFile(s.Config.GoogleSaPath))
if err != nil {
PubSubLogger.Error("failed create google pubsub client")
return err
}
s.Client = &google.GooglePubSubClient{Client: client}
return nil
}
func (s *GooglePubSubProvider) CreateSubscription(handler SubscriberHandler) error {
if handler.SubscriptionType() != SubscriptionTypePush {
return fmt.Errorf("%s is not push subscription", handler.Name())
}
if handler.Topic() == "" {
return fmt.Errorf("topic in subscription %s ir required", handler.Name())
}
if handler.PushEndpoint() == "" {
return fmt.Errorf("push endpoint in subscription %s ir required", handler.Name())
}
if s.Config.ServerDns == "" {
return errors.New("the SERVER_DSN configuration is required when using the 'push' subscription type")
}
if s.Client == nil {
if err := s.createClient(); err != nil {
return err
}
}
t := s.Client.Topic(handler.Topic())
var endpoint string
if strings.HasPrefix("/", handler.PushEndpoint()) {
endpoint = fmt.Sprintf("%s/%s%s", s.Config.ServerDns, SubscriptionPrefixEndpoint, handler.PushEndpoint())
} else {
endpoint = fmt.Sprintf("%s/%s/%s", s.Config.ServerDns, SubscriptionPrefixEndpoint, handler.PushEndpoint())
}
_, err := s.Client.CreateSubscription(context.Background(), handler.Subscription(), pubsub.SubscriptionConfig{
Topic: t.GetInstance(),
PushConfig: pubsub.PushConfig{
Endpoint: endpoint,
},
})
if strings.Contains(err.Error(), "Resource already exists in the project") {
PubSubLogger.Info("google - subscription already exists in the project", "topic", handler.Topic(), "subscription-id", handler.Subscription())
return nil
}
return err
}
func (s *GooglePubSubProvider) StartListen(handler []SubscriberHandler) error {
if err := s.validate(); err != nil {
return err
}
if s.Client == nil {
if err := s.createClient(); err != nil {
return err
}
}
var group run.Group
for _, h := range handler {
sub := s.Client.Subscription(h.Subscription())
group.Add(s.listen(sub, h), func(err error) {
os.Exit(1)
})
}
return group.Run()
}
func (s *GooglePubSubProvider) listen(subscription google.Subscription, handler SubscriberHandler) func() error {
return func() error {
PubSubLogger.Info("google - start subscribe", "name", handler.Name(), "subscription id", subscription.ID())
err := subscription.Receive(context.Background(), func(ctx context.Context, msg *pubsub.Message) {
var subCtx = subscriberContext{
cfg: s.Config,
Context: ctx,
}
if tranceID, exist := msg.Attributes["trace_id"]; exist && s.Tracer != nil {
spanId := msg.Attributes["span_id"]
spanCtx, span := extractTraceSubscriber(context.Background(), s.Tracer, tranceID, spanId, handler.Name())
subCtx.Context = spanCtx
subCtx.SetSpan(span)
}
// Process the received message
if err := handler.Consume(&subCtx, msg); err != nil {
PubSubLogger.Error("Failed consumer message", "topic", handler.Subscription(), "message", string(msg.Data))
}
// Acknowledge the message
if handler.AutoAck() {
msg.Ack()
}
})
if err == nil {
return nil
}
errMessage := err.Error()
if strings.Contains(errMessage, "code = Canceled") {
PubSubLogger.Info("google - stop listen", "name", handler.Name(), "subscription-id", subscription.ID())
return nil
}
PubSubLogger.Error("google - stop listen", "name", handler.Name(), "subscription-id", subscription.ID(), "message", err)
return err
}
}
func (s *GooglePubSubProvider) StopListen() error {
if s.Client != nil {
return s.Client.Close()
}
return nil
}
func (s *GooglePubSubProvider) Publish(ctx context.Context, topic string, message []byte) error {
if err := s.validate(); err != nil {
return err
}
if s.Client == nil {
if err := s.createClient(); err != nil {
return err
}
}
// create message
msg := pubsub.Message{
Attributes: make(map[string]string),
}
msg.Data = message
// set trace
spanCtx := trace.SpanContextFromContext(ctx)
if spanCtx.HasTraceID() {
msg.Attributes["trace_id"] = spanCtx.TraceID().String()
}
if spanCtx.HasSpanID() {
msg.Attributes["span_id"] = spanCtx.SpanID().String()
}
serverId, err := s.Client.Topic(topic).Publish(ctx, &msg).Get(context.Background())
if err != nil {
return err
}
PubSubLogger.Info("success publish message to server", "server_id", serverId)
return nil
}
func extractTraceSubscriber(ctx context.Context, tracer trace.Tracer, traceId string, spanId string, subscriberName string) (rCtx context.Context, span trace.Span) {
spanName := fmt.Sprintf("subscriber - %s", subscriberName)
if traceId == "" {
return tracer.Start(ctx, spanName)
}
var spanContextConfig trace.SpanContextConfig
spanContextConfig.TraceID, _ = trace.TraceIDFromHex(traceId)
if spanId != "" {
spanContextConfig.SpanID, _ = trace.SpanIDFromHex(spanId)
}
spanContextConfig.TraceFlags = 01
spanContextConfig.Remote = true
spanContext := trace.NewSpanContext(spanContextConfig)
traceCtx := trace.ContextWithSpanContext(ctx, spanContext)
return tracer.Start(traceCtx, spanName)
}