-
Notifications
You must be signed in to change notification settings - Fork 29
Mdc aspect implementation #488
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
Open
DmitrySadchikov
wants to merge
4
commits into
kora-projects:master
Choose a base branch
from
DmitrySadchikov:feature/mdc-aspect
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
147 changes: 147 additions & 0 deletions
147
...ging-annotation-processor/src/main/java/ru/tinkoff/kora/logging/aspect/mdc/MdcAspect.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| package ru.tinkoff.kora.logging.aspect.mdc; | ||
|
|
||
| import com.squareup.javapoet.ClassName; | ||
| import com.squareup.javapoet.CodeBlock; | ||
| import ru.tinkoff.kora.annotation.processor.common.CommonClassNames; | ||
| import ru.tinkoff.kora.annotation.processor.common.MethodUtils; | ||
| import ru.tinkoff.kora.annotation.processor.common.ProcessingErrorException; | ||
| import ru.tinkoff.kora.aop.annotation.processor.KoraAspect; | ||
|
|
||
| import javax.lang.model.element.AnnotationMirror; | ||
| import javax.lang.model.element.ExecutableElement; | ||
| import javax.lang.model.element.VariableElement; | ||
| import java.util.HashSet; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
| import java.util.Set; | ||
| import java.util.concurrent.Future; | ||
|
|
||
| import static ru.tinkoff.kora.annotation.processor.common.AnnotationUtils.findAnnotations; | ||
| import static ru.tinkoff.kora.annotation.processor.common.AnnotationUtils.isAnnotationPresent; | ||
| import static ru.tinkoff.kora.annotation.processor.common.AnnotationUtils.parseAnnotationValueWithoutDefault; | ||
| import static ru.tinkoff.kora.logging.aspect.mdc.MdcAspectClassNames.mdc; | ||
| import static ru.tinkoff.kora.logging.aspect.mdc.MdcAspectClassNames.mdcAnnotation; | ||
| import static ru.tinkoff.kora.logging.aspect.mdc.MdcAspectClassNames.mdcContainerAnnotation; | ||
|
|
||
| public class MdcAspect implements KoraAspect { | ||
|
|
||
| private static final String MDC_CONTEXT_VAR_NAME = "__mdcContext"; | ||
|
|
||
| @Override | ||
| public Set<String> getSupportedAnnotationTypes() { | ||
| return Set.of(mdcAnnotation.canonicalName(), mdcContainerAnnotation.canonicalName()); | ||
| } | ||
|
|
||
| @Override | ||
| public ApplyResult apply(ExecutableElement executableElement, String superCall, AspectContext aspectContext) { | ||
| final List<AnnotationMirror> methodAnnotations = findAnnotations(executableElement, mdcAnnotation, mdcContainerAnnotation); | ||
|
|
||
| final List<? extends VariableElement> parametersWithAnnotation = executableElement.getParameters() | ||
| .stream() | ||
| .filter(param -> isAnnotationPresent(param, mdcAnnotation)) | ||
| .toList(); | ||
|
|
||
| if (methodAnnotations.isEmpty() && parametersWithAnnotation.isEmpty()) { | ||
| final CodeBlock code = CodeBlock.builder() | ||
| .add(MethodUtils.isVoid(executableElement) ? "" : "return ") | ||
| .addStatement(KoraAspect.callSuper(executableElement, superCall)) | ||
| .build(); | ||
| return new ApplyResult.MethodBody(code); | ||
| } | ||
| if (MethodUtils.isFuture(executableElement)) { | ||
| throw new ProcessingErrorException("@Mdc can't be applied for types assignable from " + ClassName.get(Future.class), executableElement); | ||
| } | ||
| if (MethodUtils.isMono(executableElement) || MethodUtils.isFlux(executableElement)) { | ||
| throw new ProcessingErrorException("@Mdc can't be applied for types assignable from " + CommonClassNames.publisher, executableElement); | ||
| } | ||
|
|
||
| final CodeBlock.Builder currentContextBuilder = CodeBlock.builder(); | ||
| currentContextBuilder.addStatement("var $N = $T.get().values()", MDC_CONTEXT_VAR_NAME, mdc); | ||
| final CodeBlock.Builder fillMdcBuilder = CodeBlock.builder(); | ||
| final Set<String> methodKeys = fillMdcByMethodAnnotations(methodAnnotations, currentContextBuilder, fillMdcBuilder); | ||
| final Set<String> parametersKeys = fillMdcByParametersAnnotations(parametersWithAnnotation, currentContextBuilder, fillMdcBuilder); | ||
| final CodeBlock.Builder clearMdcBuilder = CodeBlock.builder(); | ||
| clearMdc(methodKeys, clearMdcBuilder); | ||
| clearMdc(parametersKeys, clearMdcBuilder); | ||
|
|
||
| final CodeBlock code = CodeBlock.builder() | ||
| .add(currentContextBuilder.build()) | ||
| .beginControlFlow("try") | ||
| .add(fillMdcBuilder.build()) | ||
| .add(MethodUtils.isVoid(executableElement) ? "" : "return ") | ||
| .addStatement(KoraAspect.callSuper(executableElement, superCall)) | ||
| .nextControlFlow("finally") | ||
| .add(clearMdcBuilder.build()) | ||
| .endControlFlow() | ||
| .build(); | ||
|
|
||
| return new ApplyResult.MethodBody(code); | ||
| } | ||
|
|
||
| private static Set<String> fillMdcByMethodAnnotations(List<AnnotationMirror> methodAnnotations, CodeBlock.Builder currentContextBuilder, CodeBlock.Builder fillMdcBuilder) { | ||
| final Set<String> keys = new HashSet<>(); | ||
| for (AnnotationMirror annotation : methodAnnotations) { | ||
| final String key = extractStringParameter(annotation, "key") | ||
| .orElseThrow(() -> new ProcessingErrorException("@Mdc annotation must have 'key' attribute", annotation.getAnnotationType().asElement())); | ||
| final String value = extractStringParameter(annotation, "value") | ||
| .orElseThrow(() -> new ProcessingErrorException("@Mdc annotation must have 'value' attribute", annotation.getAnnotationType().asElement())); | ||
| final Boolean global = parseAnnotationValueWithoutDefault(annotation, "global"); | ||
|
|
||
| if (global == null || !global) { | ||
| keys.add(key); | ||
| currentContextBuilder.addStatement("var __$N = $N.get($S)", key, MDC_CONTEXT_VAR_NAME, key); | ||
| } | ||
| if (value.startsWith("${") && value.endsWith("}")) { | ||
| fillMdcBuilder.addStatement("$T.put($S, $L)", mdc, key, value.substring(2, value.length() - 1)); | ||
| } else { | ||
| fillMdcBuilder.addStatement("$T.put($S, $S)", mdc, key, value); | ||
| } | ||
| } | ||
| return keys; | ||
| } | ||
|
|
||
| private Set<String> fillMdcByParametersAnnotations(List<? extends VariableElement> parametersWithAnnotation, CodeBlock.Builder currentContextBuilder, CodeBlock.Builder fillMdcBuilder) { | ||
| final Set<String> keys = new HashSet<>(); | ||
| for (VariableElement parameter : parametersWithAnnotation) { | ||
| final String parameterName = parameter.getSimpleName().toString(); | ||
| final AnnotationMirror firstAnnotation = findAnnotations(parameter, mdcAnnotation, mdcContainerAnnotation) | ||
| .get(0); | ||
|
|
||
| final String key = extractStringParameter(firstAnnotation, "key") | ||
| .or(() -> extractStringParameter(firstAnnotation, "value")) | ||
| .orElse(parameterName); | ||
|
|
||
| final Boolean global = parseAnnotationValueWithoutDefault(firstAnnotation, "global"); | ||
|
|
||
| fillMdcBuilder.addStatement( | ||
| "$T.put($S, $N)", | ||
| mdc, | ||
| key, | ||
| parameterName | ||
| ); | ||
|
|
||
| if (global == null || !global) { | ||
| keys.add(key); | ||
| currentContextBuilder.addStatement("var __$N = $N.get($S)", key, MDC_CONTEXT_VAR_NAME, key); | ||
| } | ||
| } | ||
| return keys; | ||
| } | ||
|
|
||
| private static Optional<String> extractStringParameter(AnnotationMirror annotation, String name) { | ||
| final String value = parseAnnotationValueWithoutDefault(annotation, name); | ||
| return Optional.ofNullable(value) | ||
| .filter(s -> !s.isBlank()); | ||
| } | ||
|
|
||
| private static void clearMdc(Set<String> keys, CodeBlock.Builder b) { | ||
| for (String key : keys) { | ||
| b.beginControlFlow("if (__$N != null)", key) | ||
| .addStatement("$T.put($S, __$N)", mdc, key, key) | ||
| .endControlFlow() | ||
| .beginControlFlow("else") | ||
| .addStatement("$T.remove($S)", mdc, key) | ||
| .endControlFlow(); | ||
| } | ||
| } | ||
| } | ||
9 changes: 9 additions & 0 deletions
9
...ation-processor/src/main/java/ru/tinkoff/kora/logging/aspect/mdc/MdcAspectClassNames.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| package ru.tinkoff.kora.logging.aspect.mdc; | ||
|
|
||
| import com.squareup.javapoet.ClassName; | ||
|
|
||
| public class MdcAspectClassNames { | ||
| public static final ClassName mdcAnnotation = ClassName.get("ru.tinkoff.kora.logging.common.annotation", "Mdc"); | ||
| public static final ClassName mdcContainerAnnotation = ClassName.get("ru.tinkoff.kora.logging.common.annotation", "Mdc", "MdcContainer"); | ||
| public static final ClassName mdc = ClassName.get("ru.tinkoff.kora.logging.common", "MDC"); | ||
| } |
15 changes: 15 additions & 0 deletions
15
...notation-processor/src/main/java/ru/tinkoff/kora/logging/aspect/mdc/MdcAspectFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| package ru.tinkoff.kora.logging.aspect.mdc; | ||
|
|
||
| import ru.tinkoff.kora.aop.annotation.processor.KoraAspect; | ||
| import ru.tinkoff.kora.aop.annotation.processor.KoraAspectFactory; | ||
|
|
||
| import javax.annotation.processing.ProcessingEnvironment; | ||
| import java.util.Optional; | ||
|
|
||
| public class MdcAspectFactory implements KoraAspectFactory { | ||
|
|
||
| @Override | ||
| public Optional<KoraAspect> create(ProcessingEnvironment processingEnvironment) { | ||
| return Optional.of(new MdcAspect()); | ||
| } | ||
| } |
1 change: 1 addition & 0 deletions
1
...in/resources/META-INF/services/ru.tinkoff.kora.aop.annotation.processor.KoraAspectFactory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| ru.tinkoff.kora.logging.aspect.LogAspectFactory | ||
| ru.tinkoff.kora.logging.aspect.mdc.MdcAspectFactory |
26 changes: 26 additions & 0 deletions
26
...ion-processor/src/test/java/ru/tinkoff/kora/logging/aspect/mdc/AbstractMdcAspectTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package ru.tinkoff.kora.logging.aspect.mdc; | ||
|
|
||
| import org.intellij.lang.annotations.Language; | ||
| import ru.tinkoff.kora.annotation.processor.common.AbstractAnnotationProcessorTest; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public abstract class AbstractMdcAspectTest extends AbstractAnnotationProcessorTest { | ||
|
|
||
| @Override | ||
| protected String commonImports() { | ||
| return super.commonImports() + """ | ||
| import ru.tinkoff.kora.logging.common.annotation.Mdc; | ||
| import ru.tinkoff.kora.logging.common.MDC; | ||
| import ru.tinkoff.kora.logging.aspect.mdc.MDCContextHolder; | ||
| import java.util.concurrent.CompletionStage; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import reactor.core.publisher.Mono; | ||
| import reactor.core.publisher.Flux; | ||
| """; | ||
| } | ||
|
|
||
| protected static List<String> sources(@Language("java") String... sources) { | ||
| return List.of(sources); | ||
| } | ||
| } |
21 changes: 21 additions & 0 deletions
21
...notation-processor/src/test/java/ru/tinkoff/kora/logging/aspect/mdc/MDCContextHolder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| package ru.tinkoff.kora.logging.aspect.mdc; | ||
|
|
||
| import ru.tinkoff.kora.logging.common.arg.StructuredArgumentWriter; | ||
|
|
||
| import java.util.Collections; | ||
| import java.util.Map; | ||
|
|
||
| public class MDCContextHolder { | ||
|
|
||
| private Map<String, StructuredArgumentWriter> mdcContext; | ||
|
|
||
| public Map<String, StructuredArgumentWriter> get() { | ||
| return mdcContext; | ||
| } | ||
|
|
||
| public void set(Map<String, StructuredArgumentWriter> mdcContext) { | ||
| this.mdcContext = mdcContext == null | ||
| ? Collections.emptyMap() | ||
| : Map.copyOf(mdcContext); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Раз уж он обязательный, то может быть и сделать его обязательным в аннотации и пусть его проверяет компилятор.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
вроде договорились что он в итоге не обязательный тк имя берется как имя аргумента
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут смысл в том, что для аннотации над методом оба параметры обязательны. А для аннотации на аргументе уже оба необязательны: