Skip to content

Commit 5d745c7

Browse files
wedamijaclaude
andcommitted
feat(spring): Send monitor config from @scheduled with @SentryCheckIn
Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 780c605 commit 5d745c7

13 files changed

Lines changed: 1093 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Features
66

7+
- Add `@SentryCheckIn(upsertMonitorConfig = true)` to send a monitor config derived from Spring `@Scheduled` with check-ins, so Sentry can create the monitor from code ([#6215](https://github.com/getsentry/sentry-java/pull/6215))
78
- Report the cellular network technology generation in `device.connection_effective_type`, for example `4g` or `5g` ([#6146](https://github.com/getsentry/sentry-java/pull/6146))
89

910
## 8.59.0

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ public final class io/sentry/spring7/cache/SentryCacheWrapper : org/springframew
136136
public abstract interface annotation class io/sentry/spring7/checkin/SentryCheckIn : java/lang/annotation/Annotation {
137137
public abstract fun heartbeat ()Z
138138
public abstract fun monitorSlug ()Ljava/lang/String;
139+
public abstract fun upsertMonitorConfig ()Z
139140
public abstract fun value ()Ljava/lang/String;
140141
}
141142

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@
2929
*/
3030
boolean heartbeat() default false;
3131

32+
/**
33+
* Set to true to send the schedule from the method's {@code @Scheduled}, so Sentry creates or
34+
* updates the monitor.
35+
*
36+
* @return true to send a monitor config, false by default
37+
*/
38+
boolean upsertMonitorConfig() default false;
39+
3240
/**
3341
* Monitor slug. If not set, no check-in will be sent.
3442
*

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

Lines changed: 118 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,32 @@
66
import io.sentry.DateUtils;
77
import io.sentry.IScopes;
88
import io.sentry.ISentryLifecycleToken;
9+
import io.sentry.MonitorConfig;
910
import io.sentry.ScopesAdapter;
1011
import io.sentry.SentryLevel;
1112
import io.sentry.protocol.SentryId;
1213
import io.sentry.time.Stopwatch;
14+
import io.sentry.util.MonitorConfigUtils;
1315
import io.sentry.util.Objects;
1416
import io.sentry.util.TracingUtils;
1517
import java.lang.reflect.Method;
18+
import java.time.Duration;
19+
import java.time.format.DateTimeParseException;
20+
import java.util.Map;
21+
import java.util.Set;
22+
import java.util.concurrent.ConcurrentHashMap;
23+
import java.util.concurrent.TimeUnit;
1624
import org.aopalliance.intercept.MethodInterceptor;
1725
import org.aopalliance.intercept.MethodInvocation;
1826
import org.jetbrains.annotations.ApiStatus;
1927
import org.jetbrains.annotations.NotNull;
2028
import org.jetbrains.annotations.Nullable;
2129
import org.springframework.aop.support.AopUtils;
2230
import org.springframework.context.EmbeddedValueResolverAware;
31+
import org.springframework.core.annotation.AnnotatedElementUtils;
2332
import org.springframework.core.annotation.AnnotationUtils;
33+
import org.springframework.scheduling.annotation.Scheduled;
34+
import org.springframework.util.ClassUtils;
2435
import org.springframework.util.ObjectUtils;
2536
import org.springframework.util.StringValueResolver;
2637

@@ -31,10 +42,19 @@
3142
@ApiStatus.Internal
3243
@Open
3344
public class SentryCheckInAdvice implements MethodInterceptor, EmbeddedValueResolverAware {
45+
// Spring before 5.3 parses crons with CronSequenceGenerator
46+
private static final boolean LEGACY_CRON_PARSER =
47+
!ClassUtils.isPresent(
48+
"org.springframework.scheduling.support.CronExpression",
49+
SentryCheckInAdvice.class.getClassLoader());
50+
3451
private final @NotNull IScopes scopes;
3552

3653
private @Nullable StringValueResolver resolver;
3754

55+
private final @NotNull Map<Method, CachedMonitorConfig> monitorConfigs =
56+
new ConcurrentHashMap<>();
57+
3858
public SentryCheckInAdvice() {
3959
this(ScopesAdapter.getInstance());
4060
}
@@ -87,6 +107,11 @@ public Object invoke(final @NotNull MethodInvocation invocation) throws Throwabl
87107
return invocation.proceed();
88108
}
89109

110+
final @Nullable MonitorConfig monitorConfig =
111+
!isHeartbeatOnly && checkInAnnotation.upsertMonitorConfig()
112+
? monitorConfig(mostSpecificMethod)
113+
: null;
114+
90115
try (final @NotNull ISentryLifecycleToken ignored =
91116
scopes.forkedScopes("SentryCheckInAdvice").makeCurrent()) {
92117
TracingUtils.startNewTrace(scopes);
@@ -98,7 +123,9 @@ public Object invoke(final @NotNull MethodInvocation invocation) throws Throwabl
98123

99124
try {
100125
if (!isHeartbeatOnly) {
101-
checkInId = scopes.captureCheckIn(new CheckIn(monitorSlug, CheckInStatus.IN_PROGRESS));
126+
final @NotNull CheckIn inProgress = new CheckIn(monitorSlug, CheckInStatus.IN_PROGRESS);
127+
inProgress.setMonitorConfig(monitorConfig);
128+
checkInId = scopes.captureCheckIn(inProgress);
102129
}
103130
return invocation.proceed();
104131
} catch (Throwable e) {
@@ -113,6 +140,96 @@ public Object invoke(final @NotNull MethodInvocation invocation) throws Throwabl
113140
}
114141
}
115142

143+
private @Nullable MonitorConfig monitorConfig(final @NotNull Method method) {
144+
return monitorConfigs.computeIfAbsent(
145+
method, key -> new CachedMonitorConfig(monitorConfigFromScheduled(key)))
146+
.config;
147+
}
148+
149+
private @Nullable MonitorConfig monitorConfigFromScheduled(final @NotNull Method method) {
150+
try {
151+
final @NotNull Set<Scheduled> schedules =
152+
AnnotatedElementUtils.findMergedRepeatableAnnotations(method, Scheduled.class);
153+
if (schedules.size() != 1) {
154+
return null;
155+
}
156+
final @NotNull Scheduled scheduled = schedules.iterator().next();
157+
// timeUnit only exists from Spring 5.3.10, so read it as an attribute
158+
final @Nullable Object timeUnitAttribute =
159+
AnnotationUtils.getAnnotationAttributes(scheduled).get("timeUnit");
160+
final @NotNull TimeUnit timeUnit =
161+
timeUnitAttribute instanceof TimeUnit
162+
? (TimeUnit) timeUnitAttribute
163+
: TimeUnit.MILLISECONDS;
164+
final @Nullable String cron = resolve(scheduled.cron());
165+
// Spring only reads the zone for a cron
166+
final @Nullable String zone =
167+
cron == null || cron.isEmpty() ? null : resolve(scheduled.zone());
168+
return MonitorConfigUtils.fromSpringScheduled(
169+
cron,
170+
zone,
171+
periodMillis(scheduled.fixedRate(), scheduled.fixedRateString(), timeUnit),
172+
periodMillis(scheduled.fixedDelay(), scheduled.fixedDelayString(), timeUnit),
173+
LEGACY_CRON_PARSER);
174+
} catch (Throwable e) {
175+
scopes
176+
.getOptions()
177+
.getLogger()
178+
.log(
179+
SentryLevel.WARNING,
180+
"Could not derive a monitor config from @Scheduled for method annotated with @SentryCheckIn.",
181+
e);
182+
return null;
183+
}
184+
}
185+
186+
private @Nullable Long periodMillis(
187+
final long value, final @NotNull String valueString, final @NotNull TimeUnit timeUnit) {
188+
if (value >= 0) {
189+
return timeUnit.toMillis(value);
190+
}
191+
final @Nullable String resolved = resolve(valueString);
192+
if (resolved == null || resolved.isEmpty()) {
193+
return null;
194+
}
195+
final @NotNull String trimmed = resolved.trim();
196+
@Nullable Long millis = null;
197+
if (trimmed.startsWith("P") || trimmed.startsWith("p")) {
198+
try {
199+
millis = Duration.parse(trimmed).toMillis();
200+
} catch (DateTimeParseException | ArithmeticException e) {
201+
// logged below
202+
}
203+
} else {
204+
millis = MonitorConfigUtils.parsePeriodMillis(trimmed, timeUnit);
205+
}
206+
if (millis == null) {
207+
scopes
208+
.getOptions()
209+
.getLogger()
210+
.log(
211+
SentryLevel.DEBUG,
212+
"Not sending a monitor config for @SentryCheckIn because the @Scheduled period '%s' could not be parsed.",
213+
trimmed);
214+
}
215+
return millis;
216+
}
217+
218+
private @Nullable String resolve(final @NotNull String value) {
219+
if (resolver == null || value.isEmpty()) {
220+
return value;
221+
}
222+
return resolver.resolveStringValue(value);
223+
}
224+
225+
private static final class CachedMonitorConfig {
226+
private final @Nullable MonitorConfig config;
227+
228+
private CachedMonitorConfig(final @Nullable MonitorConfig config) {
229+
this.config = config;
230+
}
231+
}
232+
116233
@Override
117234
public void setEmbeddedValueResolver(StringValueResolver resolver) {
118235
this.resolver = resolver;

0 commit comments

Comments
 (0)