Nestjs-OpenTelemetry icon indicating copy to clipboard operation
Nestjs-OpenTelemetry copied to clipboard

Some issue when record tracing log on guard

Open angle319 opened this issue 1 year ago • 2 comments

Hey owner, I found some problem. It's happend when same guard been use on different controller. my zipkin will receive so many guard event, like following. image image The root cause is rewrite "canActivate" which been used on guard instance. image It will loop rewriting until load all controller.

angle319 avatar May 09 '23 10:05 angle319

My solution is using other flag to condition only execution once time.

const guards = this.getGuards(controller.metatype.prototype[key]).map(
            (guard) => {
              const prototype = guard['prototype'] ?? guard;
              const traceName = `Guard->${controller.name}.${controller.metatype.prototype[key].name}.${prototype.constructor.name}`;
              const isDerGuard = /[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}/.test(prototype.constructor.name)
              const guardName = (isDerGuard) ? `Sub-Guard(Auto generate)`: prototype.constructor.name
              // same guard will loop overwrite canActivate method
              if (!prototype['singleton']) {
                prototype.canActivate = this.wrap(
                  prototype.canActivate,
                  guardName,
                  {
                    controller: controller.name,
                    guard: prototype.constructor.name,
                    method: controller.metatype.prototype[key].name,
                    scope: 'CONTROLLER_METHOD',
                  },
                );
                prototype['singleton']=true
              }
              Object.assign(prototype, this);
              this.loggerService.log(
                `Mapped ${traceName}`,
                this.constructor.name,
              );
              return guard;
            },
          );

provide for you, thanks!

angle319 avatar May 09 '23 10:05 angle319

You can see my solution.

https://github.com/Yuuki-Sakura/nestjs-open-telemetry/blob/62b44b56d3973c3a412524935e0e6f14ea6e9b2c/src/trace/injectors/guard.injector.ts#LL54C1-L81C6

Yuuki-Sakura avatar Jun 15 '23 10:06 Yuuki-Sakura