Skip to content

Commit

Permalink
feat: expose mongo read pref (#1485)
Browse files Browse the repository at this point in the history
  • Loading branch information
skynet2 authored Oct 16, 2023
1 parent 7da6fd2 commit 0124c36
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
12 changes: 10 additions & 2 deletions pkg/storage/mongodb/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ type Client struct {

func New(connString string, databaseName string, opts ...ClientOpt) (*Client, error) {
op := &clientOpts{
timeout: defaultTimeout,
timeout: defaultTimeout,
readPref: readpref.Nearest(),
}

for _, fn := range opts {
Expand All @@ -41,7 +42,7 @@ func New(connString string, databaseName string, opts ...ClientOpt) (*Client, er
mongoOpts := mongooptions.Client()
mongoOpts.ApplyURI(connString)
mongoOpts.SetWriteConcern(writeconcern.New(writeconcern.WMajority(), writeconcern.WTimeout(op.timeout)))
mongoOpts.ReadPreference = readpref.Nearest()
mongoOpts.ReadPreference = op.readPref

if op.traceProvider != nil {
mongoOpts.Monitor = otelmongo.NewMonitor(otelmongo.WithTracerProvider(op.traceProvider))
Expand Down Expand Up @@ -94,6 +95,7 @@ func (c *Client) Close() error {
type clientOpts struct {
timeout time.Duration
traceProvider trace.TracerProvider
readPref *readpref.ReadPref
}

type ClientOpt func(opts *clientOpts)
Expand All @@ -104,6 +106,12 @@ func WithTimeout(timeout time.Duration) ClientOpt {
}
}

func WithReadPref(pref *readpref.ReadPref) ClientOpt {
return func(opts *clientOpts) {
opts.readPref = pref
}
}

func WithTraceProvider(traceProvider trace.TracerProvider) ClientOpt {
return func(opts *clientOpts) {
opts.traceProvider = traceProvider
Expand Down
2 changes: 2 additions & 0 deletions pkg/storage/mongodb/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.opentelemetry.io/otel/trace"

"github.com/trustbloc/vcs/pkg/storage/mongodb"
Expand All @@ -42,6 +43,7 @@ func TestClient(t *testing.T) {

client, err := mongodb.New(mongoDBConnString, testDatabaseName,
mongodb.WithTimeout(testTimeout),
mongodb.WithReadPref(readpref.PrimaryPreferred()),
mongodb.WithTraceProvider(trace.NewNoopTracerProvider()),
)
require.NoError(t, err)
Expand Down

0 comments on commit 0124c36

Please sign in to comment.