/
registry.go
68 lines (60 loc) · 1.87 KB
/
registry.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
// Copyright (c) 2023 Silverton Data, Inc.
// You may use, distribute, and modify this code under the terms of the Apache-2.0 license, a copy of
// which may be found at https://github.com/silverton-io/buz/blob/main/LICENSE
package mongodb
import (
"context"
"github.com/rs/zerolog/log"
"github.com/silverton-io/buz/pkg/config"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoSchemaDocument struct {
ID primitive.ObjectID `bson:"_id"`
Name string `bson:"name"`
Contents string `bson:"contents"`
}
type RegistryBackend struct {
client *mongo.Client
registryCollection *mongo.Collection
}
func (b *RegistryBackend) Initialize(conf config.Backend) error {
ctx := context.Background()
opt := options.ClientOptions{
Hosts: conf.MongoHosts,
}
if conf.MongoUser != "" {
c := options.Credential{
Username: conf.MongoUser,
Password: conf.MongoPass,
}
opt.Auth = &c
}
client, err := mongo.Connect(ctx, &opt)
if err != nil {
log.Error().Err(err).Msg("🔴 could not connect to mongodb")
}
b.client = client
registryCollection := b.client.Database(conf.MongoDbName).Collection(conf.RegistryCollection)
b.registryCollection = registryCollection
return nil
}
func (b *RegistryBackend) GetRemote(schema string) (contents []byte, err error) {
ctx := context.Background()
var doc = MongoSchemaDocument{}
err = b.registryCollection.FindOne(ctx, bson.M{"name": schema}).Decode(&doc)
if err != nil {
log.Error().Err(err).Msg("🔴 could not decode document")
return nil, err
}
if err != nil {
log.Error().Err(err).Msg("🔴 could not marshal document")
return nil, err
}
return []byte(doc.Contents), nil
}
func (b *RegistryBackend) Close() {
log.Info().Msg("🟢 closing mongodb schema cache backend")
}