logmower-shipper/pkg/mongo/mongo.go
2022-11-11 17:09:12 +02:00

50 lines
1.3 KiB
Go

package mongo
import (
"context"
"fmt"
"net/url"
"time"
"go.mongodb.org/mongo-driver/mongo"
mongoOpt "go.mongodb.org/mongo-driver/mongo/options"
)
const CommandTimeout = 10 * time.Second
func GlobalTimeout(ctx context.Context) context.Context {
ctx, _ = context.WithTimeout(ctx, CommandTimeout) //nolint:lostcancel (cancelled by mongo, should be bug on them //TODO)
return ctx
}
func Initialize(ctx context.Context, uri string, opts *mongoOpt.ClientOptions) (*mongo.Collection, error) {
uriParsed, err := url.ParseRequestURI(uri)
if err != nil {
return nil, fmt.Errorf("parsing URI for database name: %w", err)
}
uriParsed.Path = uriParsed.Path[1:] // remove leading slash
if uriParsed.Path == "" {
return nil, fmt.Errorf("URI must include database name (as database to authenticate against)")
}
dbOpt := attachMetrics(opts).ApplyURI(uri)
dbClient, err := mongo.Connect(GlobalTimeout(ctx), dbOpt)
if err != nil {
return nil, fmt.Errorf("connecting to %q: %w", dbOpt.GetURI(), err)
}
if err := dbClient.Ping(GlobalTimeout(ctx), nil); err != nil {
return nil, fmt.Errorf("first ping to database: %w", err)
}
col := dbClient.Database(uriParsed.Path).Collection("logs")
if err := InitializeIndexes(GlobalTimeout(ctx), col); err != nil {
return nil, fmt.Errorf("initializing indexes: %w", err)
}
return col, nil
}