-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
76 lines (59 loc) · 1.88 KB
/
schema.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
package pubsub
import (
"context"
"io/ioutil"
"sync"
"cloud.google.com/go/pubsub"
"github.com/democracy-tools/countmein-infra/env"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
var (
pubSubSchemaClientSingleton *PubSubSchemaClientWrapper
pubSubSchemaClientOnce sync.Once
)
type PubSubSchemaClientWrapper struct {
client *pubsub.SchemaClient
}
func GetPubSubSchemaInstance() *PubSubSchemaClientWrapper {
pubSubSchemaClientOnce.Do(func() {
conf, err := google.JWTConfigFromJSON(env.GetToken(), pubsub.ScopePubSub)
if err != nil {
log.Fatalf("failed to config pubsub JWT with '%v'", err)
}
ctx := context.Background()
client, err := pubsub.NewSchemaClient(ctx, env.Project, option.WithTokenSource(conf.TokenSource(ctx)))
if err != nil {
log.Fatalf("failed to create pubsub schema client with '%v'", err)
}
pubSubSchemaClientSingleton = &PubSubSchemaClientWrapper{client: client}
})
return pubSubSchemaClientSingleton
}
// CreateProtoBufSchema creates a schema resource from a schema proto file
func (c *PubSubSchemaClientWrapper) CreateProtoBufSchema(schema, protoFile string) error {
protoSource, err := ioutil.ReadFile(protoFile)
if err != nil {
log.Errorf("failed to read file '%s' with '%v'", protoFile, err)
return err
}
config := pubsub.SchemaConfig{
Type: pubsub.SchemaProtocolBuffer,
Definition: string(protoSource),
}
s, err := c.client.CreateSchema(context.Background(), schema, config)
if err != nil {
log.Errorf("failed to create schema '%s' with '%v'", schema, err)
return err
}
log.Infof("schema '%v' created", s)
return nil
}
func (c *PubSubSchemaClientWrapper) DeleteSchema(id string) error {
log.Infof("deleting schema '%s'...", id)
return c.client.DeleteSchema(context.Background(), id)
}
func (c *PubSubSchemaClientWrapper) Close() error {
return c.client.Close()
}