diff --git a/config/mongodb.go b/config/mongodb.go index 91a87ea1..e5f8f5f1 100644 --- a/config/mongodb.go +++ b/config/mongodb.go @@ -27,6 +27,7 @@ type StreamingSettings struct { } type MongoDB struct { + URI string `yaml:"uri"` Host string `yaml:"host"` Username string `yaml:"username,omitempty"` Password string `yaml:"password,omitempty"` diff --git a/lib/mongo/config.go b/lib/mongo/config.go index 3430026e..2a8a82b3 100644 --- a/lib/mongo/config.go +++ b/lib/mongo/config.go @@ -2,22 +2,32 @@ package mongo import ( "crypto/tls" + "fmt" + "github.com/artie-labs/reader/config" "go.mongodb.org/mongo-driver/mongo/options" ) -func OptsFromConfig(cfg config.MongoDB) *options.ClientOptions { - opts := options.Client().ApplyURI(cfg.Host) - if !cfg.DisableTLS { - opts = opts.SetTLSConfig(&tls.Config{}) +func OptsFromConfig(cfg config.MongoDB) (*options.ClientOptions, error) { + var opts *options.ClientOptions + + if cfg.URI != "" { + opts = options.Client().ApplyURI(cfg.URI) + } else if cfg.Host != "" { + opts = options.Client().ApplyURI(cfg.Host) + if cfg.Username != "" && cfg.Password != "" { + opts = opts.SetAuth(options.Credential{ + Username: cfg.Username, + Password: cfg.Password, + }) + } + } else { + return nil, fmt.Errorf("mongoDB requires a URI or host") } - if cfg.Username != "" && cfg.Password != "" { - opts = opts.SetAuth(options.Credential{ - Username: cfg.Username, - Password: cfg.Password, - }) + if !cfg.DisableTLS { + opts = opts.SetTLSConfig(&tls.Config{}) } - return opts + return opts, nil } diff --git a/lib/mongo/config_test.go b/lib/mongo/config_test.go index 19bdaa30..6f47fb5f 100644 --- a/lib/mongo/config_test.go +++ b/lib/mongo/config_test.go @@ -1,9 +1,10 @@ package mongo import ( + "testing" + "github.com/artie-labs/reader/config" "github.com/stretchr/testify/assert" - "testing" ) func TestOptsFromConfig(t *testing.T) { @@ -38,4 +39,15 @@ func TestOptsFromConfig(t *testing.T) { opts := OptsFromConfig(cfg) assert.Nil(t, opts.TLSConfig) } + { + // Using URI: + cfg := config.MongoDB{ + URI: "mongodb://user:pass@localhost", + } + + opts := OptsFromConfig(cfg) + assert.NotNil(t, opts.TLSConfig) + assert.Equal(t, "user", opts.Auth.Username) + assert.Equal(t, "pass", opts.Auth.Password) + } } diff --git a/sources/mongo/mongo.go b/sources/mongo/mongo.go index 21fbc070..d3f6c315 100644 --- a/sources/mongo/mongo.go +++ b/sources/mongo/mongo.go @@ -20,7 +20,15 @@ type Source struct { } func Load(ctx context.Context, cfg config.MongoDB) (*Source, bool, error) { - client, err := mongo.Connect(ctx, mongoLib.OptsFromConfig(cfg)) + opts, err := mongoLib.OptsFromConfig(cfg) + if err != nil { + return nil, false, fmt.Errorf("options for MongoDB are invalid: %w", err) + } + if err := opts.Validate(); err != nil { + return nil, false, fmt.Errorf("validation failed for MongoDB options: %w", err) + } + + client, err := mongo.Connect(ctx, opts) if err != nil { return nil, false, fmt.Errorf("failed to connect to MongoDB: %w", err) }