micrometer-metrics / micrometer

An application observability facade for the most popular observability tools. Think SLF4J, but for observability.
https://micrometer.io
Apache License 2.0
4.46k stars 985 forks source link

Support for observing suspending functions with @Observed annotation #4827

Open ilya40umov opened 7 months ago

ilya40umov commented 7 months ago

Problem Statement

@Observed annotation, which is powered by ObservedAspect, does not seem to be able to correctly handle suspending methods. The aspect is able to invoke the suspending call, but the newly created observation does not become "current" within the suspending method.

Rationale The issue #4754 is covering additions to the Observation API, so that it can be used to observe a suspending block of code, however, a lot of Spring users may prefer to use the annotation @Observed instead.

Additional context

Seems like Spring Framework does support AOP on suspending code since some time ago: https://github.com/spring-projects/spring-framework/issues/22462. E.g. AopUtils has additional logic for dealing with invoking a suspending function.

Also, looking at this comment has made me think that ObservedAspect could actually get a mono/flux from calling ProceedingJoinPoint.proceed() and then put the newly created observation into the Reactor context via ObservationThreadLocalAccessor.KEY.

Raised initially in issues/4754#issuecomment-1977193040 by @ArvindEnvoy

ilya40umov commented 7 months ago

My curiously got better of me and I implemented a super hacky solution for this problem here: ObservedSuspendingAspect

This aspect is working with a custom annotation for now that can be added on a suspending method (but obviously @Observed annotation itself should be used in the final solution).

As I didn't find any easy way to manipulate coroutine context in an aspect, I had to get the old context from the continuation argument, tweak it a bit and then put a new, delegating continuation into the proceed()'s arguments. I'm not sure if this is even a valid use of Coroutines API 😄

ilya40umov commented 7 months ago

Assuming that the hacky solution I linked above would be okey, there is still a question of how to add this extra code to ObservedAspect. Especially, given that it lives in the micrometer-observation module, which does not really have anything to do with Kotlin.

What I think could work in this case is the following: