moleculerjs / moleculer

:rocket: Progressive microservices framework for Node.js
https://moleculer.services/
MIT License
6.17k stars 587 forks source link

Awaiting ctx.emit behave differently locally and remotely #1065

Open Embraser01 opened 2 years ago

Embraser01 commented 2 years ago

:stop_sign: Do you want to ask a question ?

Please head to the Discord chat

Prerequisites

Please answer the following questions for yourself before submitting an issue.

Current Behavior

When awaiting a ctx.emit call, the promise wait for the event to be completed locally but will resolve as soon as the event is sent on the transit when sent remotely.

A workaround for now is to remove the await but if the emit is wrapped by a middleware, it prevents it to be async.

This can be found here:

https://github.com/moleculerjs/moleculer/blob/1fa2440279ec8f242399e1f3dea30abead7c66e0/src/service-broker.js#L1357-L1389

Expected Behavior

I would expect to have a consistent behavior for both cases. I'd say I'd expect the local event to not wait for completion (matching the remote behavior).

Note: It could break tests with events that relies on this behavior.

Failure Information

Reproduce code snippet

const { ServiceBroker } = require("moleculer");

const broker = new ServiceBroker();

broker.createService({
  name: "greeter",
  actions: {
    async hello(ctx) {
      const start = Date.now();
      await ctx.emit("my-event", { test: 1 });
      this.logger.warn(`Event emit took ${Date.now() - start}ms`);
    }
  },
  events: {
    "my-event": async () => {
      await new Promise((resolve) => setTimeout(resolve, 5000));
    }
  }
});

broker.start().then(() => {
  broker
    .call("greeter.hello", { name: "CodeSandbox" })
    .catch((err) => broker.logger.error(err.message));
});

Gives an output like this: image

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

intech commented 2 years ago

@icebob This one affects emit and broadcast with an enabled balancer, which becomes a problem.