-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Jakarta Mail instrumentation for observability #5997
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
Merged
jonatan-ivanov
merged 6 commits into
micrometer-metrics:main
from
famaridon:feature/mail-observations
Jun 28, 2025
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
aeb883d
Add Jakarta Mail instrumentation for observability
famaridon f481c1c
Compile with Jakarta 9 and test with Jakarta 10
shakuzen 701d1a6
Improve code based on comments
famaridon d77b86b
make High Cardinality Key Values optional
famaridon 43ad5fa
add @author
famaridon aed3e91
Migrate to jSpecify and polish
jonatan-ivanov 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
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
156 changes: 156 additions & 0 deletions
156
...ain/java/io/micrometer/jakarta9/instrument/mail/DefaultMailSendObservationConvention.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,156 @@ | ||
| /* | ||
| * Copyright 2025 VMware, Inc. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package io.micrometer.jakarta9.instrument.mail; | ||
|
|
||
| import io.micrometer.common.KeyValue; | ||
| import io.micrometer.common.KeyValues; | ||
| import io.micrometer.common.docs.KeyName; | ||
| import jakarta.mail.Address; | ||
| import jakarta.mail.Message; | ||
| import jakarta.mail.Message.RecipientType; | ||
| import jakarta.mail.MessagingException; | ||
| import org.jspecify.annotations.Nullable; | ||
|
|
||
| import java.util.*; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| import static io.micrometer.jakarta9.instrument.mail.MailObservationDocumentation.HighCardinalityKeyNames.*; | ||
| import static io.micrometer.jakarta9.instrument.mail.MailObservationDocumentation.LowCardinalityKeyNames.*; | ||
|
|
||
| /** | ||
| * Default implementation for {@link MailSendObservationConvention}. | ||
| * | ||
| * @since 1.16.0 | ||
| * @author famaridon | ||
| */ | ||
| public class DefaultMailSendObservationConvention implements MailSendObservationConvention { | ||
|
|
||
| private static final String UNKNOWN = "unknown"; | ||
|
|
||
| @Override | ||
| public String getName() { | ||
| return "mail.send"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getContextualName(MailSendObservationContext context) { | ||
| return "mail send"; | ||
| } | ||
|
|
||
| @Override | ||
| public KeyValues getLowCardinalityKeyValues(MailSendObservationContext context) { | ||
| return KeyValues.of(serverAddress(context), serverPort(context), networkProtocolName(context)); | ||
| } | ||
|
|
||
| @Override | ||
| public KeyValues getHighCardinalityKeyValues(MailSendObservationContext context) { | ||
| Message message = context.getCarrier(); | ||
| List<KeyValue> values = new ArrayList<>(); | ||
| smtpMessageSubject(message).ifPresent(values::add); | ||
| smtpMessageFrom(message).ifPresent(values::add); | ||
| smtpMessageRecipients(message, RecipientType.TO).ifPresent(values::add); | ||
| smtpMessageRecipients(message, RecipientType.CC).ifPresent(values::add); | ||
| smtpMessageRecipients(message, RecipientType.BCC).ifPresent(values::add); | ||
|
|
||
| return KeyValues.of(values); | ||
| } | ||
|
|
||
| private KeyValue serverAddress(MailSendObservationContext context) { | ||
| String host = context.getHost(); | ||
| if (host == null || host.isEmpty()) { | ||
| return SERVER_ADDRESS.withValue(UNKNOWN); | ||
| } | ||
| return SERVER_ADDRESS.withValue(host); | ||
| } | ||
|
|
||
| private KeyValue serverPort(MailSendObservationContext context) { | ||
| int port = context.getPort(); | ||
| if (port <= 0) { | ||
| return SERVER_PORT.withValue(UNKNOWN); | ||
| } | ||
| return SERVER_PORT.withValue(String.valueOf(port)); | ||
| } | ||
|
|
||
| private KeyValue networkProtocolName(MailSendObservationContext context) { | ||
| String protocol = context.getProtocol(); | ||
| if (protocol == null || protocol.isEmpty()) { | ||
| return NETWORK_PROTOCOL_NAME.withValue(UNKNOWN); | ||
| } | ||
| return NETWORK_PROTOCOL_NAME.withValue(protocol); | ||
| } | ||
|
|
||
| private Optional<KeyValue> smtpMessageSubject(@Nullable Message message) { | ||
| if (message == null) { | ||
| return Optional.empty(); | ||
| } | ||
| return safeExtractValue(SMTP_MESSAGE_SUBJECT, () -> Optional.ofNullable(message.getSubject())); | ||
| } | ||
|
|
||
| private Optional<KeyValue> smtpMessageFrom(@Nullable Message message) { | ||
| if (message == null) { | ||
| return Optional.empty(); | ||
| } | ||
| return safeExtractValue(SMTP_MESSAGE_FROM, () -> addressesToValue(message.getFrom())); | ||
| } | ||
|
|
||
| private Optional<KeyValue> smtpMessageRecipients(@Nullable Message message, RecipientType recipientType) { | ||
| if (message == null) { | ||
| return Optional.empty(); | ||
| } | ||
| MailObservationDocumentation.HighCardinalityKeyNames key = MailObservationDocumentation.HighCardinalityKeyNames | ||
| .valueOf("SMTP_MESSAGE_" + recipientType.toString().toUpperCase(Locale.ROOT)); | ||
| return safeExtractValue(key, () -> addressesToValue(message.getRecipients(recipientType))); | ||
| } | ||
|
|
||
| Optional<KeyValue> smtpMessageId(@Nullable Message message) { | ||
| if (message == null) { | ||
| return Optional.empty(); | ||
| } | ||
| return safeExtractValue(SMTP_MESSAGE_ID, () -> extractHeaderValue(message, "Message-ID")); | ||
| } | ||
|
|
||
| private Optional<String> extractHeaderValue(Message message, String headerName) throws MessagingException { | ||
| String[] header = message.getHeader(headerName); | ||
| if (header == null || header.length == 0) { | ||
| return Optional.empty(); | ||
| } | ||
| return Optional.of(String.join(", ", header)); | ||
| } | ||
|
|
||
| private Optional<KeyValue> safeExtractValue(KeyName key, ValueExtractor extractor) { | ||
| try { | ||
| return extractor.extract().map(key::withValue); | ||
| } | ||
| catch (MessagingException ex) { | ||
| return Optional.of(key.withValue(UNKNOWN)); | ||
| } | ||
| } | ||
|
|
||
| private Optional<String> addressesToValue(Address @Nullable [] addresses) { | ||
| if (addresses == null || addresses.length == 0) { | ||
| return Optional.empty(); | ||
| } | ||
| String value = Arrays.stream(addresses).map(Address::toString).collect(Collectors.joining(", ")); | ||
| return Optional.of(value); | ||
| } | ||
|
|
||
| private interface ValueExtractor { | ||
|
|
||
| Optional<String> extract() throws MessagingException; | ||
|
|
||
| } | ||
|
|
||
| } |
110 changes: 110 additions & 0 deletions
110
...-jakarta9/src/main/java/io/micrometer/jakarta9/instrument/mail/InstrumentedTransport.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,110 @@ | ||
| /* | ||
| * Copyright 2025 VMware, Inc. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package io.micrometer.jakarta9.instrument.mail; | ||
|
|
||
| import io.micrometer.observation.Observation; | ||
| import io.micrometer.observation.ObservationConvention; | ||
| import io.micrometer.observation.ObservationRegistry; | ||
| import jakarta.mail.*; | ||
| import org.jspecify.annotations.Nullable; | ||
|
|
||
| /** | ||
| * Wraps a {@link Transport} so that it is instrumented with a Micrometer | ||
| * {@link Observation}. | ||
| * | ||
| * @since 1.16.0 | ||
| * @author famaridon | ||
| */ | ||
| public class InstrumentedTransport extends Transport { | ||
|
|
||
| private static final DefaultMailSendObservationConvention DEFAULT_CONVENTION = new DefaultMailSendObservationConvention(); | ||
|
|
||
| private final ObservationRegistry observationRegistry; | ||
|
|
||
| private final Transport delegate; | ||
|
|
||
| private final @Nullable String protocol; | ||
|
|
||
| private @Nullable String host; | ||
|
|
||
| private int port; | ||
|
|
||
| private final @Nullable ObservationConvention<MailSendObservationContext> customConvention; | ||
|
|
||
| /** | ||
| * Create an instrumented transport using the | ||
| * {@link DefaultMailSendObservationConvention default} {@link ObservationConvention}. | ||
| * @param session session for the delegate transport | ||
| * @param delegate transport to instrument | ||
| * @param observationRegistry registry for the observations | ||
| */ | ||
| public InstrumentedTransport(Session session, Transport delegate, ObservationRegistry observationRegistry) { | ||
| this(session, delegate, observationRegistry, null); | ||
| } | ||
|
|
||
| /** | ||
| * Create an instrumented transport with a custom {@link MailSendObservationConvention | ||
| * convention}. | ||
| * @param session session for the delegate transport | ||
| * @param delegate transport to instrument | ||
| * @param observationRegistry registry for the observations | ||
| * @param customConvention override the convention to apply to the instrumentation | ||
| */ | ||
| public InstrumentedTransport(Session session, Transport delegate, ObservationRegistry observationRegistry, | ||
| @Nullable ObservationConvention<MailSendObservationContext> customConvention) { | ||
| super(session, delegate.getURLName()); | ||
| this.protocol = this.url.getProtocol(); | ||
| this.delegate = delegate; | ||
| this.observationRegistry = observationRegistry; | ||
| this.customConvention = customConvention; | ||
| } | ||
|
|
||
| @Override | ||
| public void connect(String host, int port, String user, String password) throws MessagingException { | ||
| this.delegate.connect(host, port, user, password); | ||
| this.host = host; | ||
| this.port = port; | ||
| } | ||
|
|
||
| @Override | ||
| public void sendMessage(Message msg, Address[] addresses) throws MessagingException { | ||
| Observation observation = MailObservationDocumentation.MAIL_SEND.observation(this.customConvention, | ||
| DEFAULT_CONVENTION, () -> new MailSendObservationContext(msg, this.protocol, this.host, this.port), | ||
| observationRegistry); | ||
|
|
||
| observation.start(); | ||
| try (Observation.Scope ignore = observation.openScope()) { | ||
| this.delegate.sendMessage(msg, addresses); | ||
| // the Message-Id is set by the Transport (from the SMTP server) after sending | ||
| DEFAULT_CONVENTION.smtpMessageId(msg).ifPresent(observation::highCardinalityKeyValue); | ||
| } | ||
| catch (MessagingException error) { | ||
| observation.error(error); | ||
| throw error; | ||
| } | ||
| finally { | ||
| observation.stop(); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public synchronized void close() throws MessagingException { | ||
| this.delegate.close(); | ||
| this.host = null; | ||
| this.port = 0; | ||
jonatan-ivanov marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.