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

Better for service discovery #11114

Merged
merged 1 commit into from
Dec 20, 2021
Merged

Better for service discovery #11114

merged 1 commit into from
Dec 20, 2021

Conversation

hustxiaoc
Copy link
Contributor

@hustxiaoc hustxiaoc commented Dec 17, 2021

For some situation, the mongo server host is dynamic and we need to create a new mongodb client when the current client is disconnected, so it's much better if we can call setClient multiple times.

const createMongoClient = async () => {

  const host = await service.discover('mongodb.host');

  const uri = `mongodb://${host.uri}/test`;

  const mongoClient: MongoClient = await MongoClient.connect(uri, {
    autoReconnect: false,
  });

  client.setClient(mongoClient);

  client.once('disconnected', async () => {
    mongoClient.close();

    // @ts-ignore   we need to get rid of this
    client.client = null;

    while(true) {
      await sleep(3 * 1e3);
      try {
        if (client.readyState === mongoose.STATES.disconnected) {
          await createMongoClient();
        }  
        break;
      } catch (err) {
        console.error(err);
      }
    }        
  });
}

await createMongoClient();

@vkarpov15
Copy link
Collaborator

Supporting this sort of functionality is risky, because we don't have a good way to cancel operations in flight. For example, suppose you're in the middle of a populate() when you call setClient() - main query executes on the first MongoClient, 2nd query may execute on a separate client connected to a separate database.

That being said, I don't see any reason why we can't merge this. If you choose to use this behavior, just choose to be aware of the risks: calling setClient() does not cancel any operations that are in flight.

@vkarpov15 vkarpov15 added this to the 6.1.3 milestone Dec 20, 2021
@vkarpov15 vkarpov15 merged commit c072e57 into Automattic:master Dec 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants