From 18ee57d1d1eab4dd638bd9def7f5b05e36ac72b3 Mon Sep 17 00:00:00 2001 From: Shubham Date: Tue, 30 Apr 2024 22:36:30 +0530 Subject: [PATCH] Update Mongo dialer when MONGO_SERVER_URL rotates 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. --- docstore/mongodocstore/urls.go | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/docstore/mongodocstore/urls.go b/docstore/mongodocstore/urls.go index 3e7ce282e2..b6d2ed14d4 100644 --- a/docstore/mongodocstore/urls.go +++ b/docstore/mongodocstore/urls.go @@ -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) }