Spaces:
Paused
Paused
File size: 4,646 Bytes
83a59ca | 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 | package repositories
import (
"context"
"net/url"
"reflect"
"time"
"github.com/NdoleStudio/stacktrace"
"github.com/google/uuid"
"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"
collectionContacts = "contacts"
)
// 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.Propagatef(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.Propagatef(err, "cannot connect to MongoDB Atlas")
}
if err = client.Ping(pingCtx, nil); err != nil {
return nil, stacktrace.Propagatef(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.Propagatef(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.Propagatef(err, "cannot parse MongoDB URI [%s]", uri)
}
appName := parsed.Query().Get("appName")
if appName == "" {
return "", stacktrace.NewErrorf("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{{Key: "user_id", Value: 1}, {Key: "owner", Value: 1}, {Key: "timestamp", Value: -1}}},
})
if err != nil {
return stacktrace.Propagatef(err, "cannot create indexes on heartbeats collection")
}
// Heartbeat monitors indexes
monitorsCol := db.Collection(collectionHeartbeatMonitors)
_, err = monitorsCol.Indexes().CreateMany(ctx, []mongo.IndexModel{
{Keys: bson.D{{Key: "user_id", Value: 1}, {Key: "owner", Value: 1}}},
})
if err != nil {
return stacktrace.Propagatef(err, "cannot create indexes on heartbeat_monitors collection")
}
contactsCol := db.Collection(collectionContacts)
_, err = contactsCol.Indexes().CreateMany(ctx, contactMongoIndexModels())
if err != nil {
return stacktrace.Propagatef(err, "cannot create indexes on contacts collection")
}
return nil
}
func contactMongoIndexModels() []mongo.IndexModel {
return []mongo.IndexModel{
{Keys: bson.D{
{Key: "user_id", Value: 1},
{Key: "updated_at", Value: -1},
{Key: "_id", Value: -1},
}},
{Keys: bson.D{
{Key: "user_id", Value: 1},
{Key: "name", Value: 1},
{Key: "_id", Value: 1},
}},
{Keys: bson.D{
{Key: "user_id", Value: 1},
{Key: "phone_numbers", Value: 1},
{Key: "updated_at", Value: 1},
{Key: "_id", Value: 1},
}},
}
}
|