forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongodb.go
More file actions
127 lines (105 loc) · 3.77 KB
/
Copy pathmongodb.go
File metadata and controls
127 lines (105 loc) · 3.77 KB
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
package repositories
import (
"context"
"fmt"
"net/url"
"reflect"
"time"
"github.com/google/uuid"
"github.com/palantir/stacktrace"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo"
)
const (
collectionHeartbeats = "heartbeats"
collectionHeartbeatMonitors = "heartbeat_monitors"
)
// uuidEncodeValue encodes uuid.UUID as a BSON string
func uuidEncodeValue(_ bson.EncodeContext, vw bson.ValueWriter, val reflect.Value) error {
u := val.Interface().(uuid.UUID)
return vw.WriteString(u.String())
}
// uuidDecodeValue decodes a BSON string into uuid.UUID
func uuidDecodeValue(_ bson.DecodeContext, vr bson.ValueReader, val reflect.Value) error {
str, err := vr.ReadString()
if err != nil {
return err
}
parsed, err := uuid.Parse(str)
if err != nil {
return err
}
val.Set(reflect.ValueOf(parsed))
return nil
}
// newMongoRegistry creates a BSON registry that encodes uuid.UUID as strings
func newMongoRegistry() *bson.Registry {
rb := bson.NewRegistry()
rb.RegisterTypeEncoder(reflect.TypeOf(uuid.UUID{}), bson.ValueEncoderFunc(uuidEncodeValue))
rb.RegisterTypeDecoder(reflect.TypeOf(uuid.UUID{}), bson.ValueDecoderFunc(uuidDecodeValue))
return rb
}
// NewMongoDB creates a new *mongo.Database connection to MongoDB Atlas and ensures indexes.
// The database name is derived from the appName query parameter in the URI.
func NewMongoDB(uri string) (*mongo.Database, error) {
dbName, err := parseMongoDBName(uri)
if err != nil {
return nil, stacktrace.Propagate(err, "cannot parse database name from MongoDB URI")
}
pingCtx, pingCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer pingCancel()
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
registry := newMongoRegistry()
opts := options.Client().
ApplyURI(uri).
SetServerAPIOptions(serverAPI).
SetRegistry(registry).
SetMonitor(otelmongo.NewMonitor())
client, err := mongo.Connect(opts)
if err != nil {
return nil, stacktrace.Propagate(err, "cannot connect to MongoDB Atlas")
}
if err = client.Ping(pingCtx, nil); err != nil {
return nil, stacktrace.Propagate(err, "cannot ping MongoDB Atlas")
}
db := client.Database(dbName)
indexCtx, indexCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer indexCancel()
if err = createMongoIndexes(indexCtx, db); err != nil {
return nil, stacktrace.Propagate(err, "cannot create MongoDB indexes")
}
return db, nil
}
// parseMongoDBName extracts the appName query parameter from the MongoDB URI to use as the database name
func parseMongoDBName(uri string) (string, error) {
parsed, err := url.Parse(uri)
if err != nil {
return "", stacktrace.Propagate(err, fmt.Sprintf("cannot parse MongoDB URI [%s]", uri))
}
appName := parsed.Query().Get("appName")
if appName == "" {
return "", stacktrace.NewError("MongoDB URI is missing the 'appName' query parameter which is used as the database name")
}
return appName, nil
}
func createMongoIndexes(ctx context.Context, db *mongo.Database) error {
// Heartbeats indexes
heartbeatsCol := db.Collection(collectionHeartbeats)
_, err := heartbeatsCol.Indexes().CreateMany(ctx, []mongo.IndexModel{
{Keys: bson.D{{"user_id", 1}, {"owner", 1}, {"timestamp", -1}}},
})
if err != nil {
return stacktrace.Propagate(err, "cannot create indexes on heartbeats collection")
}
// Heartbeat monitors indexes
monitorsCol := db.Collection(collectionHeartbeatMonitors)
_, err = monitorsCol.Indexes().CreateMany(ctx, []mongo.IndexModel{
{Keys: bson.D{{"user_id", 1}, {"owner", 1}}},
})
if err != nil {
return stacktrace.Propagate(err, "cannot create indexes on heartbeat_monitors collection")
}
return nil
}