Skip to content

Commit 4d8eb11

Browse files
authored
Upgrade to the mongo20 client library (#95)
1 parent fd6f706 commit 4d8eb11

File tree

18 files changed

+136
-136
lines changed

18 files changed

+136
-136
lines changed

api/api_gomux.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818

1919
"github.com/gorilla/websocket"
2020
httpSwagger "github.com/swaggo/http-swagger"
21-
"go.mongodb.org/mongo-driver/bson/primitive"
21+
"go.mongodb.org/mongo-driver/v2/bson"
2222

2323
"github.com/square/etre"
2424
"github.com/square/etre/app"
@@ -494,13 +494,13 @@ func (api *API) id(next http.Handler) http.Handler {
494494
rc := ctx.Value(reqKey).(*req)
495495

496496
var err error
497-
var entityId primitive.ObjectID
497+
var entityId bson.ObjectID
498498

499499
id := r.PathValue("id") // 1. from URL
500500
if id == "" {
501501
err = ErrMissingParam.New("missing id param")
502502
} else {
503-
entityId, err = primitive.ObjectIDFromHex(id) // 2. convert to/validate as ObjectID
503+
entityId, err = bson.ObjectIDFromHex(id) // 2. convert to/validate as ObjectID
504504
if err != nil {
505505
err = ErrInvalidParam.New("id '%s' is not a valid ObjectID: %v", id, err)
506506
}
@@ -1309,8 +1309,8 @@ func (api *API) WriteResult(rc *req, w http.ResponseWriter, ids interface{}, err
13091309
diffs := ids.([]etre.Entity)
13101310
writes = make([]etre.Write, len(diffs))
13111311
for i, diff := range diffs {
1312-
// _id from db is primitive.ObjectID, convert to string
1313-
id := diff["_id"].(primitive.ObjectID).Hex()
1312+
// _id from db is bson.ObjectID, convert to string
1313+
id := diff["_id"].(bson.ObjectID).Hex()
13141314
writes[i] = etre.Write{
13151315
EntityId: id,
13161316
URI: api.addr + etre.API_ROOT + "/entity/" + id,
@@ -1336,9 +1336,9 @@ func (api *API) WriteResult(rc *req, w http.ResponseWriter, ids interface{}, err
13361336
// Entity from DeleteLabel
13371337
diff := ids.(etre.Entity)
13381338

1339-
// _id from db is primitive.ObjectID, convert to string
1339+
// _id from db is bson.ObjectID, convert to string
13401340
if diff != nil && diff["_id"] != nil {
1341-
id = diff["_id"].(primitive.ObjectID).Hex()
1341+
id = diff["_id"].(bson.ObjectID).Hex()
13421342
}
13431343
writes = []etre.Write{
13441344
{

api/api_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import (
1616

1717
"github.com/stretchr/testify/assert"
1818
"github.com/stretchr/testify/require"
19-
"go.mongodb.org/mongo-driver/bson/primitive"
19+
"go.mongodb.org/mongo-driver/v2/bson"
2020

2121
"github.com/square/etre"
2222
"github.com/square/etre/api"
@@ -60,9 +60,9 @@ var testEntities = []etre.Entity{
6060
var testEntityIds = []string{"59f10d2a5669fc79103a0000", "59f10d2a5669fc79103a1111", "59f10d2a5669fc79103a2222"}
6161

6262
var (
63-
testEntityId0, _ = primitive.ObjectIDFromHex(testEntityIds[0])
64-
testEntityId1, _ = primitive.ObjectIDFromHex(testEntityIds[1])
65-
testEntityId2, _ = primitive.ObjectIDFromHex(testEntityIds[2])
63+
testEntityId0, _ = bson.ObjectIDFromHex(testEntityIds[0])
64+
testEntityId1, _ = bson.ObjectIDFromHex(testEntityIds[1])
65+
testEntityId2, _ = bson.ObjectIDFromHex(testEntityIds[2])
6666
)
6767

6868
var testEntitiesWithObjectIDs = []etre.Entity{

cdc/changestream/server.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ import (
1111

1212
"github.com/square/etre"
1313

14-
"go.mongodb.org/mongo-driver/bson"
15-
"go.mongodb.org/mongo-driver/mongo"
14+
"go.mongodb.org/mongo-driver/v2/bson"
15+
"go.mongodb.org/mongo-driver/v2/mongo"
1616
)
1717

1818
var (

cdc/changestream/server_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ import (
99

1010
"github.com/stretchr/testify/assert"
1111
"github.com/stretchr/testify/require"
12-
"go.mongodb.org/mongo-driver/bson"
13-
"go.mongodb.org/mongo-driver/mongo"
12+
"go.mongodb.org/mongo-driver/v2/bson"
13+
"go.mongodb.org/mongo-driver/v2/mongo"
1414

1515
"github.com/square/etre"
1616
"github.com/square/etre/cdc"

cdc/store.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ import (
1111
"sort"
1212
"time"
1313

14-
"go.mongodb.org/mongo-driver/bson"
15-
"go.mongodb.org/mongo-driver/mongo"
16-
"go.mongodb.org/mongo-driver/mongo/options"
14+
"go.mongodb.org/mongo-driver/v2/bson"
15+
"go.mongodb.org/mongo-driver/v2/mongo"
16+
"go.mongodb.org/mongo-driver/v2/mongo/options"
1717

1818
"github.com/square/etre"
1919
)
@@ -107,8 +107,10 @@ func (s *store) Read(f Filter) ([]etre.CDCEvent, error) {
107107
// etre.CDC to match so, below, cursor.All() doesn't have to realloc the
108108
// slice. For small fetches, this is overkill, but it makes large fetchs
109109
// (>100k events) very quick and efficient.
110-
opts := options.Count().SetMaxTime(5 * time.Second)
111-
count, err := s.coll.CountDocuments(context.TODO(), q, opts)
110+
opts := options.Count()
111+
cctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
112+
defer cancel()
113+
count, err := s.coll.CountDocuments(cctx, q, opts)
112114
if err != nil {
113115
return nil, err
114116
}

cdc/store_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ import (
1212

1313
"github.com/stretchr/testify/assert"
1414
"github.com/stretchr/testify/require"
15-
"go.mongodb.org/mongo-driver/bson"
16-
"go.mongodb.org/mongo-driver/mongo"
17-
"go.mongodb.org/mongo-driver/mongo/options"
15+
"go.mongodb.org/mongo-driver/v2/bson"
16+
"go.mongodb.org/mongo-driver/v2/mongo"
17+
"go.mongodb.org/mongo-driver/v2/mongo/options"
1818

1919
"github.com/square/etre"
2020
"github.com/square/etre/cdc"
@@ -47,7 +47,7 @@ func setup(t *testing.T, fallbackFile string, wrp cdc.RetryPolicy) cdc.Store {
4747
// First time, create unique index on "x"
4848
if coll == nil {
4949
iv := cdcColl.Indexes()
50-
if _, err := iv.DropAll(context.TODO()); err != nil {
50+
if err := iv.DropAll(context.TODO()); err != nil {
5151
t.Fatal(err)
5252
}
5353
idx := mongo.IndexModel{

db/db.go

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@
33
package db
44

55
import (
6-
"context"
76
"crypto/tls"
87
"crypto/x509"
98
"io/ioutil"
109
"log"
1110
"time"
1211

13-
"go.mongodb.org/mongo-driver/mongo"
14-
"go.mongodb.org/mongo-driver/mongo/options"
12+
"go.mongodb.org/mongo-driver/v2/mongo"
13+
"go.mongodb.org/mongo-driver/v2/mongo/options"
1514

1615
"github.com/square/etre/config"
1716
)
@@ -68,24 +67,11 @@ func (d Default) Connect(cfg config.DatasourceConfig) (*mongo.Client, error) {
6867
log.Printf("WARNING: No database username for %s specified in config. Authentication will fail unless MongoDB access control is disabled.", cfg.URL)
6968
}
7069

71-
client, err := mongo.NewClient(opts)
72-
if err != nil {
73-
return nil, err
74-
}
75-
76-
// mongo.Connect() does not actually connect:
77-
// The Client.Connect method starts background goroutines to monitor the
78-
// state of the deployment and does not do any I/O in the main goroutine to
79-
// prevent the main goroutine from blocking. Therefore, it will not error if
80-
// the deployment is down.
81-
// https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo?tab=doc#Connect
70+
// mongo.Connect() does not actually connect to the database.
8271
// The caller must call client.Ping() to actually connect. Consequently,
8372
// we don't need a context here. As long as there's not a bug in the mongo
8473
// driver, this won't block.
85-
if err := client.Connect(context.Background()); err != nil {
86-
return nil, err
87-
}
88-
return client, nil
74+
return mongo.Connect(opts)
8975
}
9076

9177
func loadTLS(cfg config.DatasourceConfig) (*tls.Config, error) {

entity/entity.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ import (
88
"github.com/square/etre"
99
"github.com/square/etre/query"
1010

11-
"go.mongodb.org/mongo-driver/bson"
12-
"go.mongodb.org/mongo-driver/bson/primitive"
13-
"go.mongodb.org/mongo-driver/mongo"
11+
"go.mongodb.org/mongo-driver/v2/bson"
12+
"go.mongodb.org/mongo-driver/v2/mongo"
1413
)
1514

1615
type DbError struct {
@@ -66,16 +65,16 @@ func Filter(q query.Query) bson.M {
6665
if p.Label == etre.META_LABEL_ID {
6766
switch p.Value.(type) {
6867
case string:
69-
id, _ := primitive.ObjectIDFromHex(p.Value.(string))
68+
id, _ := bson.ObjectIDFromHex(p.Value.(string))
7069
filter[p.Label] = bson.M{operatorMap[p.Operator]: id}
7170
case []string:
7271
vals := p.Value.([]string)
73-
oids := make([]primitive.ObjectID, len(vals))
72+
oids := make([]bson.ObjectID, len(vals))
7473
for i, v := range vals {
75-
oids[i], _ = primitive.ObjectIDFromHex(v)
74+
oids[i], _ = bson.ObjectIDFromHex(v)
7675
}
7776
filter[p.Label] = bson.M{operatorMap[p.Operator]: oids}
78-
case primitive.ObjectID:
77+
case bson.ObjectID:
7978
filter[p.Label] = bson.M{operatorMap[p.Operator]: p.Value}
8079
default:
8180
panic(fmt.Sprintf("invalid _id value type: %T", p.Value))

entity/store.go

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ package entity
44

55
import (
66
"context"
7+
"errors"
78
"time"
89

9-
"go.mongodb.org/mongo-driver/bson"
10-
"go.mongodb.org/mongo-driver/bson/primitive"
11-
"go.mongodb.org/mongo-driver/mongo"
12-
"go.mongodb.org/mongo-driver/mongo/options"
10+
"go.mongodb.org/mongo-driver/v2/bson"
11+
"go.mongodb.org/mongo-driver/v2/mongo"
12+
"go.mongodb.org/mongo-driver/v2/mongo/options"
1313

1414
"github.com/square/etre"
1515
"github.com/square/etre/cdc"
@@ -58,7 +58,17 @@ func (s store) ReadEntities(ctx context.Context, entityType string, q query.Quer
5858
// "es -u node.metacluster zone=pd" returns a list of unique metacluster names.
5959
// This is 10x faster than "es node.metacluster zone=pd | sort -u".
6060
if len(f.ReturnLabels) == 1 && f.Distinct {
61-
values, err := c.Distinct(ctx, f.ReturnLabels[0], Filter(q))
61+
dr := c.Distinct(ctx, f.ReturnLabels[0], Filter(q))
62+
if err := dr.Err(); err != nil {
63+
nfe := mongo.ErrNoDocuments
64+
if errors.Is(err, nfe) {
65+
// No documents found, return empty slice
66+
return []etre.Entity{}, nil
67+
}
68+
return nil, s.dbError(ctx, err, "db-read-distinct")
69+
}
70+
var values []string
71+
err := dr.Decode(&values)
6272
if err != nil {
6373
return nil, s.dbError(ctx, err, "db-read-distinct")
6474
}
@@ -122,7 +132,7 @@ func (s store) CreateEntities(ctx context.Context, wo WriteOp, entities []etre.E
122132

123133
now := time.Now().UnixNano()
124134
for i := range entities {
125-
entities[i]["_id"] = primitive.NewObjectID()
135+
entities[i]["_id"] = bson.NewObjectID()
126136
entities[i]["_type"] = wo.EntityType
127137
entities[i]["_rev"] = int64(0)
128138
entities[i]["_created"] = now
@@ -132,7 +142,7 @@ func (s store) CreateEntities(ctx context.Context, wo WriteOp, entities []etre.E
132142
if err != nil {
133143
return newIds, s.dbError(ctx, err, "db-insert")
134144
}
135-
id := res.InsertedID.(primitive.ObjectID)
145+
id := res.InsertedID.(bson.ObjectID)
136146
newIds = append(newIds, id.Hex())
137147

138148
// Create a CDC event.
@@ -195,7 +205,7 @@ func (s store) UpdateEntities(ctx context.Context, wo WriteOp, q query.Query, pa
195205
}
196206
opts := options.FindOneAndUpdate().SetProjection(p)
197207

198-
nextId := map[string]primitive.ObjectID{}
208+
nextId := map[string]bson.ObjectID{}
199209
for cursor.Next(ctx) {
200210
if err := cursor.Decode(&nextId); err != nil {
201211
return diffs, s.dbError(ctx, err, "db-cursor-decode")
@@ -222,7 +232,7 @@ func (s store) UpdateEntities(ctx context.Context, wo WriteOp, q query.Query, pa
222232

223233
cp := cdcPartial{
224234
op: "u",
225-
id: orig["_id"].(primitive.ObjectID),
235+
id: orig["_id"].(bson.ObjectID),
226236
rev: orig.Rev() + 1,
227237
old: &old,
228238
new: &patch,
@@ -266,7 +276,7 @@ func (s store) DeleteEntities(ctx context.Context, wo WriteOp, q query.Query) ([
266276
deleted = append(deleted, old)
267277
ce := cdcPartial{
268278
op: "d",
269-
id: old["_id"].(primitive.ObjectID),
279+
id: old["_id"].(bson.ObjectID),
270280
old: &old,
271281
new: nil,
272282
rev: old.Rev() + 1,
@@ -286,7 +296,7 @@ func (s store) DeleteLabel(ctx context.Context, wo WriteOp, label string) (etre.
286296
panic("invalid entity type passed to DeleteLabel: " + wo.EntityType)
287297
}
288298

289-
id, _ := primitive.ObjectIDFromHex(wo.EntityId)
299+
id, _ := bson.ObjectIDFromHex(wo.EntityId)
290300
filter := bson.M{"_id": id}
291301
update := bson.M{
292302
"$unset": bson.M{label: ""}, // removes label, Mongo expects "" (see $unset docs)
@@ -322,7 +332,7 @@ func (s store) DeleteLabel(ctx context.Context, wo WriteOp, label string) (etre.
322332

323333
cp := cdcPartial{
324334
op: "u",
325-
id: old["_id"].(primitive.ObjectID),
335+
id: old["_id"].(bson.ObjectID),
326336
new: &new,
327337
old: &old,
328338
rev: old.Rev() + 1,
@@ -355,7 +365,7 @@ func (s store) dbError(ctx context.Context, err error, errType string) error {
355365
// which makes a complete CDCEvent from the partial and a WriteOp.
356366
type cdcPartial struct {
357367
op string
358-
id primitive.ObjectID
368+
id bson.ObjectID
359369
old *etre.Entity
360370
new *etre.Entity
361371
rev int64

0 commit comments

Comments
 (0)