tile38/internal/endpoint/pubsub.go

99 lines
1.6 KiB
Go
Raw Permalink Normal View History

2020-05-19 18:11:31 +03:00
package endpoint
import (
"context"
"fmt"
"sync"
"time"
2021-07-10 13:59:27 +03:00
"cloud.google.com/go/pubsub"
"google.golang.org/api/option"
2020-05-19 18:11:31 +03:00
)
const pubsubExpiresAfter = time.Second * 30
// SQSConn is an endpoint connection
type PubSubConn struct {
2021-07-10 13:59:27 +03:00
mu sync.Mutex
ep Endpoint
svc *pubsub.Client
topic *pubsub.Topic
ex bool
t time.Time
2020-05-19 18:11:31 +03:00
}
func (conn *PubSubConn) close() {
if conn.svc != nil {
conn.svc.Close()
conn.svc = nil
}
}
// Send sends a message
func (conn *PubSubConn) Send(msg string) error {
conn.mu.Lock()
defer conn.mu.Unlock()
if conn.ex {
return errExpired
}
ctx := context.Background()
conn.t = time.Now()
if conn.svc == nil {
var creds option.ClientOption
2020-05-22 11:03:55 +03:00
var svc *pubsub.Client
var err error
2020-05-19 18:11:31 +03:00
credPath := conn.ep.PubSub.CredPath
2020-05-22 11:03:55 +03:00
if credPath != "" {
2020-05-19 18:11:31 +03:00
creds = option.WithCredentialsFile(credPath)
2020-05-22 11:03:55 +03:00
svc, err = pubsub.NewClient(ctx, conn.ep.PubSub.Project, creds)
2020-05-19 18:11:31 +03:00
} else {
2020-05-22 11:03:55 +03:00
svc, err = pubsub.NewClient(ctx, conn.ep.PubSub.Project)
2020-05-19 18:11:31 +03:00
}
2020-05-22 11:03:55 +03:00
2020-05-19 18:11:31 +03:00
if err != nil {
fmt.Println(err)
return err
}
topic := svc.Topic(conn.ep.PubSub.Topic)
conn.svc = svc
conn.topic = topic
}
// Send message
res := conn.topic.Publish(ctx, &pubsub.Message{
Data: []byte(msg),
})
_, err := res.Get(ctx)
if err != nil {
fmt.Println(err)
return err
}
return nil
}
func (conn *PubSubConn) Expired() bool {
conn.mu.Lock()
defer conn.mu.Unlock()
if !conn.ex {
2021-07-10 13:59:27 +03:00
if time.Since(conn.t) > pubsubExpiresAfter {
2020-05-19 18:11:31 +03:00
conn.ex = true
conn.close()
}
}
return conn.ex
}
func newPubSubConn(ep Endpoint) *PubSubConn {
return &PubSubConn{
ep: ep,
t: time.Now(),
}
}