Skip to content

Commit

Permalink
Update Mongo dialer when MONGO_SERVER_URL rotates
Browse files Browse the repository at this point in the history
Prior to this commit, the dialer for MongoDB was generated once from
MONGO_SERVER_URL environment variable but was never updated even when
the environment variable was updated in subsequent calls. While this
works fine when MONGO_SERVER_URL is not expected to update, but as
MONGO_SERVER_URL also contains the credentials to connect to MongoDB,
it's a fairly common use case to rotate these credentials (and hence the
environment variable) at regular intervals.

This commit fixes that and updates the dialer when MONGO_SERVER_URL is
updated.
  • Loading branch information
concaf committed May 1, 2024
1 parent 3f641fd commit 18ee57d
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions docstore/mongodocstore/urls.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,27 +34,31 @@ func init() {
// defaultDialer dials a default Mongo server based on the environment variable
// MONGO_SERVER_URL.
type defaultDialer struct {
init sync.Once
opener *URLOpener
err error
mongoServerURL string
mu sync.Mutex
opener *URLOpener
err error
}

func (o *defaultDialer) OpenCollectionURL(ctx context.Context, u *url.URL) (*docstore.Collection, error) {
o.init.Do(func() {
serverURL := os.Getenv("MONGO_SERVER_URL")
if serverURL == "" {
o.err = errors.New("MONGO_SERVER_URL environment variable is not set")
return
}
client, err := Dial(ctx, serverURL)
o.mu.Lock()
defer o.mu.Unlock()
currentEnv := os.Getenv("MONGO_SERVER_URL")

if currentEnv == "" {
o.err = errors.New("MONGO_SERVER_URL environment variable is not set")
return nil, fmt.Errorf("open collection %s: %v", u, o.err)
}

// If MONGO_SERVER_URL has been updated, then update o.opener as well
if currentEnv != o.mongoServerURL {
client, err := Dial(ctx, currentEnv)
if err != nil {
o.err = fmt.Errorf("failed to dial default Mongo server at %q: %v", serverURL, err)
return
o.err = fmt.Errorf("failed to dial default Mongo server at %q: %v", currentEnv, err)
return nil, fmt.Errorf("open collection %s: %v", u, o.err)
}
o.mongoServerURL = currentEnv
o.opener = &URLOpener{Client: client}
})
if o.err != nil {
return nil, fmt.Errorf("open collection %s: %v", u, o.err)
}
return o.opener.OpenCollectionURL(ctx, u)
}
Expand Down

0 comments on commit 18ee57d

Please sign in to comment.