Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: expose mongo read pref #1485

Merged
merged 1 commit into from
Oct 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading