logmower-shipper/pkg/mongo/mongo.go

50 lines
1.3 KiB
Go
Raw Normal View History

2022-11-09 16:07:28 +00:00
package mongo
import (
"context"
"fmt"
"net/url"
2022-11-11 15:09:12 +00:00
"time"
2022-11-09 16:07:28 +00:00
"go.mongodb.org/mongo-driver/mongo"
2022-11-11 15:09:12 +00:00
mongoOpt "go.mongodb.org/mongo-driver/mongo/options"
2022-11-09 16:07:28 +00:00
)
2022-11-11 15:09:12 +00:00
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) {
2022-11-09 16:07:28 +00:00
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)")
}
2022-11-11 15:09:12 +00:00
dbOpt := attachMetrics(opts).ApplyURI(uri)
2022-11-09 16:07:28 +00:00
2022-11-11 15:09:12 +00:00
dbClient, err := mongo.Connect(GlobalTimeout(ctx), dbOpt)
2022-11-09 16:07:28 +00:00
if err != nil {
return nil, fmt.Errorf("connecting to %q: %w", dbOpt.GetURI(), err)
}
2022-11-11 15:09:12 +00:00
if err := dbClient.Ping(GlobalTimeout(ctx), nil); err != nil {
2022-11-09 19:55:54 +00:00
return nil, fmt.Errorf("first ping to database: %w", err)
}
2022-11-09 16:07:28 +00:00
col := dbClient.Database(uriParsed.Path).Collection("logs")
2022-11-11 15:09:12 +00:00
if err := InitializeIndexes(GlobalTimeout(ctx), col); err != nil {
2022-11-09 16:07:28 +00:00
return nil, fmt.Errorf("initializing indexes: %w", err)
}
return col, nil
}