aboutsummaryrefslogtreecommitdiff
path: root/db/mongodb/client.go
blob: 1f3815dfd904196d6762a6bd8e36dcfa79e1585e (plain)
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
package mongodb

import (
	"context"
	"fmt"
	"net"
	"net/url"
	"strings"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"

	"code.crute.us/mcrute/golib/vault"
)

// AnyInTopLevelArray is just a convenience method so apps don't have to repeat
// this ugly bson expression.
func AnyInTopLevelArray(k string, v interface{}) bson.M {
	return bson.M{k: bson.M{"$all": bson.A{v}}}
}

type Mongo struct {
	client *mongo.Client
	db     *mongo.Database
}

func Connect(ctx context.Context, uri string, vc vault.VaultClient) (*Mongo, error) {
	db := &Mongo{}

	// Prefix uri with mongodb:// unless it already includes one of the
	// standard prefixes (only these two are valid). Otherwise if scheme is
	// omitted then url parsing will fail to capture the username for Vault
	// lookup.
	if !strings.HasPrefix(uri, "mongodb://") && !strings.HasPrefix(uri, "mongodb+srv://") {
		uri = "mongodb://" + uri
	}

	u, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}

	// The username provided by the user (there should be no
	// password) will be a reference to a vault material with the
	// prefix database/creds/. This needs to be replaced with the real
	// username/password pair fetched from Vault before attempting to
	// connect.
	cred, err := vc.DbCredential(ctx, u.User.Username())
	if err != nil {
		return nil, err
	}
	u.User = url.UserPassword(cred.Username, cred.Password)

	// User may imply the default port
	if u.Port() == "" {
		u.Host = net.JoinHostPort(u.Host, "27017")
	}

	// Users should generally authenticate against the admin collection so
	// they should only specify it if they need to override that.
	if u.Query().Get("authSource") == "" {
		pq := u.Query()
		pq.Add("authSource", "admin")
		u.RawQuery = pq.Encode()
	}

	cs, err := connstring.ParseAndValidate(u.String())
	if err != nil {
		return nil, err
	}

	client, err := mongo.Connect(ctx, options.Client().ApplyURI(u.String()))
	if err != nil {
		return nil, err
	}

	db.client = client
	db.db = client.Database(cs.Database)

	return db, nil
}

func (m *Mongo) Collection(name string) *mongo.Collection {
	return m.db.Collection(name)
}

func (m *Mongo) FindAllByFilter(ctx context.Context, cn string, filter interface{}, out interface{}) error {
	res, err := m.db.Collection(cn).Find(ctx, filter)
	if err != nil {
		return err
	}

	if err = res.All(ctx, out); err != nil {
		return err
	}

	return nil
}

func (m *Mongo) FindAll(ctx context.Context, cn string, out interface{}) error {
	return m.FindAllByFilter(ctx, cn, bson.D{}, out)
}

func (m *Mongo) FindOneByFilter(ctx context.Context, cn string, filter interface{}, out interface{}) error {
	if err := m.db.Collection(cn).FindOne(ctx, filter).Decode(out); err != nil {
		return err
	}

	return nil
}

func (m *Mongo) FindOneById(ctx context.Context, cn string, id string, out interface{}) error {
	return m.FindOneByFilter(ctx, cn, bson.M{"_id": id}, out)
}

func (m *Mongo) InsertOne(ctx context.Context, cn string, in interface{}) error {
	_, err := m.db.Collection(cn).InsertOne(ctx, in)
	if err != nil {
		return err
	}

	return nil
}

func (m *Mongo) ReplaceOneByFilter(ctx context.Context, cn string, filter interface{}, in interface{}) error {
	tp := true
	opts := &options.ReplaceOptions{Upsert: &tp}
	if _, err := m.db.Collection(cn).ReplaceOne(ctx, filter, in, opts); err != nil {
		return err
	}

	return nil
}

func (m *Mongo) ReplaceOneById(ctx context.Context, cn string, id string, in interface{}) error {
	return m.ReplaceOneByFilter(ctx, cn, bson.M{"_id": id}, in)
}

func (m *Mongo) DeleteOneByFilter(ctx context.Context, cn string, filter interface{}) error {
	dr, err := m.db.Collection(cn).DeleteOne(ctx, filter)
	if err != nil {
		return err
	}

	if dr.DeletedCount != 1 {
		return fmt.Errorf("Invalid deletion record count %d not 1", dr.DeletedCount)
	}

	return nil
}

func (m *Mongo) DeleteOneById(ctx context.Context, cn string, id string) error {
	return m.DeleteOneByFilter(ctx, cn, bson.M{"_id": id})
}