Skip to content

Commit 8158e3c

Browse files
wedamijaclaude
andauthored
feat(spring): Add an option to monitor all @scheduled methods in Spring Boot 4 (#6277)
* ref(core): Add MonitorConfigUtils to convert schedules to monitor configs Framework-free conversion of a 6 field cron expression, fixed rate or fixed delay into a MonitorConfig, plus period parsing, so the Spring and Quartz integrations can share it. * fix(core): Only send monitor configs Sentry reads the same way Return no config when day of month and day of week are both set, for cron syntax Sentry rejects, and for zones that are not IANA region IDs. Whole-hour fixed offsets map to Etc/GMT zones. Intervals use hours or days when they divide evenly. * ref(core): Add MonitorConfigUtils.fromSpringScheduled Move the Spring day-of-week rewrite and the JVM default zone rule into core so the three Spring modules share them. * fix(core): Return no config for stepped single value ranges Spring and Quartz run 10-10/2 only at 10, cronsim steps to the field max. * fix(core): Read Spring crons per parser and skip fixed delays Spring before 5.3 steps day of month */n from 0 and can run at midnight when both day fields are set; read its crons that way. Spring 5.3 runs #5 in months without a fifth weekday, so return null for it. A fixed delay drifts from any interval, so it gets no config. * feat(spring): Send monitor config from @scheduled with @SentryCheckIn Co-Authored-By: Claude <noreply@anthropic.com> * feat(spring): Send @scheduled monitor config by default Co-Authored-By: Claude <noreply@anthropic.com> * ref(spring): Shorten upsertMonitorConfig Javadoc Co-Authored-By: Claude <noreply@anthropic.com> * fix(core): Keep Sunday-only day of week ranges SUN-SUN was rewritten to 0-7, which crontab reads as every day. Co-Authored-By: Claude <noreply@anthropic.com> * fix(spring): Only catch runtime exceptions when deriving monitor config Co-Authored-By: Claude <noreply@anthropic.com> * ref(spring): Shorten upsertMonitorConfig Javadoc Co-Authored-By: Claude <noreply@anthropic.com> * feat(spring-jakarta): Monitor all @scheduled methods with sentry.monitor-scheduled-tasks Adds sentry.monitor-scheduled-tasks and sentry.exclude-scheduled-tasks to Spring Boot 3. Methods without @SentryCheckIn get a slug from the class and method name and send their @scheduled schedule as the monitor config. Co-Authored-By: Claude <noreply@anthropic.com> * changelog Co-Authored-By: Claude <noreply@anthropic.com> * feat(spring): Monitor all @scheduled methods in Spring Boot 2 Co-Authored-By: Claude <noreply@anthropic.com> * docs(changelog): Link Spring Boot 2 PR Co-Authored-By: Claude <noreply@anthropic.com> * feat(spring): Monitor all @scheduled methods in Spring Boot 4 Co-Authored-By: Claude <noreply@anthropic.com> * docs(changelog): Link Spring Boot 4 PR Co-Authored-By: Claude <noreply@anthropic.com> * fix(spring-jakarta): Skip reactive @scheduled methods when monitoring all tasks Spring calls reactive and suspend @scheduled methods once at startup and subscribes to the result on each run, so check-ins around the call would only be sent once. Co-Authored-By: Claude <noreply@anthropic.com> * fix(spring): Skip reactive @scheduled methods when monitoring all tasks Same fix as the Spring Boot 3 copy. Co-Authored-By: Claude <noreply@anthropic.com> * fix(spring-7): Skip reactive @scheduled methods when monitoring all tasks Same fix as the Spring Boot 3 copy. Co-Authored-By: Claude <noreply@anthropic.com> * fix(spring): Skip jobs with unsupported schedules when monitoring all jobs * fix(spring): Skip jobs with unsupported schedules when monitoring all jobs * fix(spring): Skip jobs with unsupported schedules when monitoring all jobs * ref(spring): Use pattern-matching instanceof for the @scheduled time unit * fix(spring): Satisfy NullAway in the Spring 7 scheduled check-in advice * fix(core): Use a 2 minute check-in margin for crons with fixed seconds Dropping a non-zero seconds field makes check-ins arrive up to 59s after the expected minute, which a 1 minute margin barely covers. * fix(spring): Default upsertMonitorConfig to false and read @scheduled like Spring Existing @SentryCheckIn users shouldn't have their monitors changed on upgrade, so sending the schedule is opt-in. Find @scheduled with Spring's own lookup so an overriding method doesn't inherit a parent's schedule. * fix(spring): Find @scheduled tasks to monitor the way Spring does An overriding method without @scheduled isn't scheduled by Spring, so don't monitor it either. * fix(spring): Find @scheduled tasks to monitor the way Spring does An overriding method without @scheduled isn't scheduled by Spring, so don't monitor it either. * fix(spring): Find @scheduled tasks to monitor the way Spring does An overriding method without @scheduled isn't scheduled by Spring, so don't monitor it either. * feat(spring): Warn when two @scheduled methods share a monitor slug Derived slugs use only the short class name and method name, so different methods can map to the same slug and share one monitor. Log a warning the first time that happens so users can set an explicit slug. * feat(spring): Warn when two @scheduled methods share a monitor slug Derived slugs use only the short class name and method name, so different methods can map to the same slug and share one monitor. Log a warning the first time that happens so users can set an explicit slug. * feat(spring): Warn when two @scheduled methods share a monitor slug Derived slugs use only the short class name and method name, so different methods can map to the same slug and share one monitor. Log a warning the first time that happens so users can set an explicit slug. * ref(spring): Reuse the target class for the slug collision check Use the same class for the task name and the collision check so both see one value. * ref(spring): Reuse the target class for the slug collision check Use the same class for the task name and the collision check so both see one value. * fix(spring): Skip private and static @scheduled methods when monitoring all tasks Spring invokes private and static scheduled methods on the target, so the proxy never sees them. Don't match them, so they aren't proxied for nothing. * fix(spring): Skip private and static @scheduled methods when monitoring all tasks Spring invokes private and static scheduled methods on the target, so the proxy never sees them. Don't match them, so they aren't proxied for nothing. * fix(spring): Skip private and static @scheduled methods when monitoring all tasks Spring invokes private and static scheduled methods on the target, so the proxy never sees them. Don't match them, so they aren't proxied for nothing. --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e29145a commit 8158e3c

9 files changed

Lines changed: 658 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
### Features
1111

12-
- Monitor every Spring `@Scheduled` method with Sentry Crons by setting `sentry.monitor-scheduled-tasks=true`, without adding `@SentryCheckIn` to each method. Sentry creates each monitor from the method's `@Scheduled` schedule. Exclude methods with `sentry.exclude-scheduled-tasks` ([#6275](https://github.com/getsentry/sentry-java/pull/6275), [#6276](https://github.com/getsentry/sentry-java/pull/6276))
12+
- Monitor every Spring `@Scheduled` method with Sentry Crons by setting `sentry.monitor-scheduled-tasks=true`, without adding `@SentryCheckIn` to each method. Sentry creates each monitor from the method's `@Scheduled` schedule. Exclude methods with `sentry.exclude-scheduled-tasks` ([#6275](https://github.com/getsentry/sentry-java/pull/6275), [#6276](https://github.com/getsentry/sentry-java/pull/6276), [#6277](https://github.com/getsentry/sentry-java/pull/6277))
1313
- Quartz `SentryJobListener` can send a monitor config derived from the trigger with check-ins, so Sentry creates or updates the monitor from code. Set the `sentry-upsert-monitor-config` job or trigger data key to `"true"` to send the schedule ([#6216](https://github.com/getsentry/sentry-java/pull/6216))
1414
- Send a monitor config derived from Spring `@Scheduled` with `@SentryCheckIn` check-ins, so Sentry creates or updates the monitor from code. Set `@SentryCheckIn(upsertMonitorConfig = true)` to send the schedule ([#6215](https://github.com/getsentry/sentry-java/pull/6215))
1515

‎sentry-spring-7/api/sentry-spring-7.api‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ public abstract interface annotation class io/sentry/spring7/checkin/SentryCheck
148148
public class io/sentry/spring7/checkin/SentryCheckInAdvice : org/aopalliance/intercept/MethodInterceptor, org/springframework/context/EmbeddedValueResolverAware {
149149
public fun <init> ()V
150150
public fun <init> (Lio/sentry/IScopes;)V
151+
public fun <init> (Lio/sentry/IScopes;Z)V
151152
public fun invoke (Lorg/aopalliance/intercept/MethodInvocation;)Ljava/lang/Object;
152153
public fun setEmbeddedValueResolver (Lorg/springframework/util/StringValueResolver;)V
153154
}
@@ -168,6 +169,11 @@ public class io/sentry/spring7/checkin/SentryQuartzConfiguration {
168169
public fun schedulerFactoryBeanCustomizer ()Lorg/springframework/boot/quartz/autoconfigure/SchedulerFactoryBeanCustomizer;
169170
}
170171

172+
public final class io/sentry/spring7/checkin/SentryScheduledCheckInPointcut : org/springframework/aop/support/StaticMethodMatcherPointcut {
173+
public fun <init> (Ljava/util/List;)V
174+
public fun matches (Ljava/lang/reflect/Method;Ljava/lang/Class;)Z
175+
}
176+
171177
public final class io/sentry/spring7/checkin/SentrySchedulerFactoryBeanCustomizer : org/springframework/boot/quartz/autoconfigure/SchedulerFactoryBeanCustomizer {
172178
public fun <init> ()V
173179
public fun customize (Lorg/springframework/scheduling/quartz/SchedulerFactoryBean;)V

‎sentry-spring-7/src/main/java/io/sentry/spring7/checkin/SentryCheckInAdvice.java‎

Lines changed: 104 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,16 @@
1515
import io.sentry.util.Objects;
1616
import io.sentry.util.TracingUtils;
1717
import java.lang.reflect.Method;
18+
import java.nio.charset.StandardCharsets;
1819
import java.time.Duration;
1920
import java.time.format.DateTimeParseException;
21+
import java.util.Locale;
2022
import java.util.Map;
2123
import java.util.Set;
2224
import java.util.concurrent.ConcurrentHashMap;
2325
import java.util.concurrent.TimeUnit;
26+
import java.util.regex.Pattern;
27+
import java.util.zip.CRC32;
2428
import org.aopalliance.intercept.MethodInterceptor;
2529
import org.aopalliance.intercept.MethodInvocation;
2630
import org.jetbrains.annotations.ApiStatus;
@@ -49,19 +53,38 @@ public class SentryCheckInAdvice implements MethodInterceptor, EmbeddedValueReso
4953
"org.springframework.scheduling.support.CronExpression",
5054
SentryCheckInAdvice.class.getClassLoader());
5155

56+
private static final @NotNull Pattern WORD_BOUNDARY =
57+
Pattern.compile("(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])");
58+
private static final int MAX_SLUG_LENGTH = 50;
59+
5260
private final @NotNull IScopes scopes;
5361

62+
private final boolean monitorScheduledTasks;
63+
5464
private @Nullable StringValueResolver resolver;
5565

5666
private final @NotNull Map<Method, CachedMonitorConfig> monitorConfigs =
5767
new ConcurrentHashMap<>();
5868

69+
private final @NotNull Map<String, String> derivedSlugOwners = new ConcurrentHashMap<>();
70+
71+
private final @NotNull Set<String> collidingSlugs = ConcurrentHashMap.newKeySet();
72+
5973
public SentryCheckInAdvice() {
6074
this(ScopesAdapter.getInstance());
6175
}
6276

6377
public SentryCheckInAdvice(final @NotNull IScopes scopes) {
78+
this(scopes, false);
79+
}
80+
81+
/**
82+
* @param monitorScheduledTasks whether to also monitor {@code @Scheduled} methods without {@link
83+
* SentryCheckIn}, using a slug derived from the class and method name
84+
*/
85+
public SentryCheckInAdvice(final @NotNull IScopes scopes, final boolean monitorScheduledTasks) {
6486
this.scopes = Objects.requireNonNull(scopes, "scopes are required");
87+
this.monitorScheduledTasks = monitorScheduledTasks;
6588
}
6689

6790
@Override
@@ -75,6 +98,25 @@ public SentryCheckInAdvice(final @NotNull IScopes scopes) {
7598
SentryCheckIn checkInAnnotation =
7699
AnnotationUtils.findAnnotation(mostSpecificMethod, SentryCheckIn.class);
77100
if (checkInAnnotation == null) {
101+
if (monitorScheduledTasks && isScheduled(mostSpecificMethod)) {
102+
final @NotNull Class<?> targetClass =
103+
target != null ? target.getClass() : mostSpecificMethod.getDeclaringClass();
104+
final @NotNull String taskName = scheduledTaskName(targetClass, mostSpecificMethod);
105+
final @Nullable MonitorConfig monitorConfig = monitorConfig(mostSpecificMethod);
106+
if (monitorConfig == null) {
107+
scopes
108+
.getOptions()
109+
.getLogger()
110+
.log(
111+
SentryLevel.DEBUG,
112+
"Not monitoring %s because Sentry Crons can't express its @Scheduled schedule.",
113+
taskName);
114+
return invocation.proceed();
115+
}
116+
final @NotNull String monitorSlug = scheduledTaskSlug(taskName);
117+
warnOnSlugCollision(monitorSlug, targetClass, mostSpecificMethod);
118+
return captureCheckIns(invocation, monitorSlug, false, monitorConfig);
119+
}
78120
return invocation.proceed();
79121
}
80122

@@ -114,7 +156,15 @@ public SentryCheckInAdvice(final @NotNull IScopes scopes) {
114156
!isHeartbeatOnly && checkInAnnotation.upsertMonitorConfig()
115157
? monitorConfig(mostSpecificMethod)
116158
: null;
159+
return captureCheckIns(invocation, monitorSlug, isHeartbeatOnly, monitorConfig);
160+
}
117161

162+
private @Nullable Object captureCheckIns(
163+
final @NotNull MethodInvocation invocation,
164+
final @NotNull String monitorSlug,
165+
final boolean isHeartbeatOnly,
166+
final @Nullable MonitorConfig monitorConfig)
167+
throws Throwable {
118168
try (final @NotNull ISentryLifecycleToken ignored =
119169
scopes.forkedScopes("SentryCheckInAdvice").makeCurrent()) {
120170
TracingUtils.startNewTrace(scopes);
@@ -143,6 +193,58 @@ public SentryCheckInAdvice(final @NotNull IScopes scopes) {
143193
}
144194
}
145195

196+
private void warnOnSlugCollision(
197+
final @NotNull String monitorSlug,
198+
final @NotNull Class<?> targetClass,
199+
final @NotNull Method method) {
200+
final @NotNull String identity =
201+
ClassUtils.getUserClass(targetClass).getName() + "." + method.getName();
202+
final @Nullable String owner = derivedSlugOwners.putIfAbsent(monitorSlug, identity);
203+
if (owner != null && !owner.equals(identity) && collidingSlugs.add(monitorSlug)) {
204+
scopes
205+
.getOptions()
206+
.getLogger()
207+
.log(
208+
SentryLevel.WARNING,
209+
"Monitor slug \"%s\" is used by both %s and %s, so their check-ins go to one monitor. Add @SentryCheckIn(\"your-slug\") to one of them.",
210+
monitorSlug,
211+
owner,
212+
identity);
213+
}
214+
}
215+
216+
static boolean isScheduled(final @NotNull Method method) {
217+
return !AnnotatedElementUtils.getMergedRepeatableAnnotations(
218+
method, Scheduled.class, Schedules.class)
219+
.isEmpty();
220+
}
221+
222+
/** {@code ClassName.methodName}, with nested classes as {@code Outer.Inner}. */
223+
static @NotNull String scheduledTaskName(
224+
final @NotNull Class<?> targetClass, final @NotNull Method method) {
225+
return ClassUtils.getShortName(ClassUtils.getUserClass(targetClass)) + "." + method.getName();
226+
}
227+
228+
static @NotNull String scheduledTaskSlug(final @NotNull String taskName) {
229+
final @NotNull String slug =
230+
WORD_BOUNDARY
231+
.matcher(taskName)
232+
.replaceAll("-")
233+
.toLowerCase(Locale.ROOT)
234+
.replaceAll("[^a-z0-9]+", "-")
235+
.replaceAll("^-+|-+$", "");
236+
if (slug.length() <= MAX_SLUG_LENGTH) {
237+
return slug;
238+
}
239+
// keep truncated slugs unique
240+
final @NotNull CRC32 crc = new CRC32();
241+
crc.update(slug.getBytes(StandardCharsets.UTF_8));
242+
final @NotNull String hash = String.format(Locale.ROOT, "%08x", crc.getValue());
243+
return slug.substring(0, MAX_SLUG_LENGTH - hash.length() - 1).replaceAll("-+$", "")
244+
+ "-"
245+
+ hash;
246+
}
247+
146248
private @Nullable MonitorConfig monitorConfig(final @NotNull Method method) {
147249
return monitorConfigs.computeIfAbsent(
148250
method, key -> new CachedMonitorConfig(monitorConfigFromScheduled(key)))
@@ -177,10 +279,7 @@ public SentryCheckInAdvice(final @NotNull IScopes scopes) {
177279
scopes
178280
.getOptions()
179281
.getLogger()
180-
.log(
181-
SentryLevel.WARNING,
182-
"Could not derive a monitor config from @Scheduled for method annotated with @SentryCheckIn.",
183-
e);
282+
.log(SentryLevel.WARNING, "Could not derive a monitor config from @Scheduled.", e);
184283
return null;
185284
}
186285
}
@@ -211,7 +310,7 @@ public SentryCheckInAdvice(final @NotNull IScopes scopes) {
211310
.getLogger()
212311
.log(
213312
SentryLevel.DEBUG,
214-
"Not sending a monitor config for @SentryCheckIn because the @Scheduled period '%s' could not be parsed.",
313+
"Not sending a monitor config because the @Scheduled period '%s' could not be parsed.",
215314
trimmed);
216315
}
217316
return millis;
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package io.sentry.spring7.checkin;
2+
3+
import io.sentry.FilterString;
4+
import java.lang.reflect.Method;
5+
import java.lang.reflect.Modifier;
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
import org.jetbrains.annotations.ApiStatus;
9+
import org.jetbrains.annotations.NotNull;
10+
import org.jetbrains.annotations.Nullable;
11+
import org.springframework.aop.support.AopUtils;
12+
import org.springframework.aop.support.StaticMethodMatcherPointcut;
13+
import org.springframework.core.ReactiveAdapterRegistry;
14+
import org.springframework.core.annotation.AnnotationUtils;
15+
import org.springframework.util.ClassUtils;
16+
17+
/**
18+
* Matches {@code @Scheduled} methods without {@link SentryCheckIn}, except excluded ones. Excludes
19+
* match the task name ({@code ClassName.methodName}) exactly or as a regex.
20+
*/
21+
@ApiStatus.Internal
22+
public final class SentryScheduledCheckInPointcut extends StaticMethodMatcherPointcut {
23+
private final @NotNull List<FilterString> excludedScheduledTasks = new ArrayList<>();
24+
25+
public SentryScheduledCheckInPointcut(final @Nullable List<String> excludedScheduledTasks) {
26+
if (excludedScheduledTasks != null) {
27+
for (final @NotNull String task : excludedScheduledTasks) {
28+
if (!task.trim().isEmpty()) {
29+
this.excludedScheduledTasks.add(new FilterString(task.trim()));
30+
}
31+
}
32+
}
33+
}
34+
35+
@Override
36+
public boolean matches(final @NotNull Method method, final @NotNull Class<?> targetClass) {
37+
final @NotNull Class<?> userClass = ClassUtils.getUserClass(targetClass);
38+
// CGLIB can't intercept these, and Spring calls private and static methods on the target
39+
final int modifiers = method.getModifiers();
40+
if (Modifier.isFinal(userClass.getModifiers())
41+
|| Modifier.isFinal(modifiers)
42+
|| Modifier.isPrivate(modifiers)
43+
|| Modifier.isStatic(modifiers)) {
44+
return false;
45+
}
46+
final @NotNull Method specificMethod = AopUtils.getMostSpecificMethod(method, userClass);
47+
if (!SentryCheckInAdvice.isScheduled(specificMethod)
48+
|| AnnotationUtils.findAnnotation(specificMethod, SentryCheckIn.class) != null) {
49+
return false;
50+
}
51+
// Spring calls reactive and suspend methods once and subscribes to the result on each run
52+
if (specificMethod.getParameterCount() > 0
53+
|| ReactiveAdapterRegistry.getSharedInstance().getAdapter(specificMethod.getReturnType())
54+
!= null) {
55+
return false;
56+
}
57+
final @NotNull String taskName =
58+
SentryCheckInAdvice.scheduledTaskName(userClass, specificMethod);
59+
for (final @NotNull FilterString excluded : excludedScheduledTasks) {
60+
if (excluded.getFilterString().equals(taskName) || excluded.matches(taskName)) {
61+
return false;
62+
}
63+
}
64+
return true;
65+
}
66+
}

0 commit comments

Comments
 (0)