Skip to content

Commit d565fed

Browse files
authored
feat(crons): Mark @monitor jobs so scheduler integrations skip them (#8198)
### Description Marks functions wrapped with `@sentry_sdk.monitor`, so scheduler integrations can skip jobs that already send their own check-ins. The arq integration now does this, so those jobs don't report twice. Also moves arq's time zone lookup into `sentry_sdk/crons/utils.py` so other cron integrations can share it, and stops sending names that aren't IANA zones (like tzlocal's `local`), which Sentry would reject. This is the base for #7840 (APScheduler), which uses both. ### Testing New arq test for a `@sentry_sdk.monitor` cron job. The existing arq time zone tests cover the helper.
1 parent 5a099b8 commit d565fed

4 files changed

Lines changed: 57 additions & 16 deletions

File tree

‎sentry_sdk/crons/decorator.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ async def inner(*args: "P.args", **kwargs: "P.kwargs") -> "R":
126126
with self:
127127
return await fn(*args, **kwargs)
128128

129+
inner._sentry_monitored = True # type: ignore[attr-defined]
129130
return inner
130131

131132
def _sync_wrapper(self, fn: "Callable[P, R]") -> "Callable[P, R]":
@@ -134,4 +135,5 @@ def inner(*args: "P.args", **kwargs: "P.kwargs") -> "R":
134135
with self:
135136
return fn(*args, **kwargs)
136137

138+
inner._sentry_monitored = True # type: ignore[attr-defined]
137139
return inner

‎sentry_sdk/crons/utils.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import re
2+
from datetime import timedelta, timezone
13
from typing import TYPE_CHECKING
24

35
if TYPE_CHECKING:
6+
from datetime import tzinfo
47
from typing import Optional, Tuple
58

69
from sentry_sdk._types import MonitorConfigSchedule, MonitorConfigScheduleUnit
@@ -27,3 +30,26 @@ def _get_interval_schedule(seconds: float) -> "Optional[MonitorConfigSchedule]":
2730
"unit": unit,
2831
}
2932
return None
33+
34+
35+
# IANA zone names start with an uppercase letter. This rejects names like
36+
# "local" or "localtime" that tzlocal can give a zone.
37+
_IANA_TIMEZONE_NAME = re.compile(r"[A-Z][A-Za-z0-9._+-]*(?:/[A-Za-z0-9._+-]+)*")
38+
39+
40+
def _get_timezone_name(tz: "tzinfo") -> "Optional[str]":
41+
"""
42+
Return the IANA name of the timezone, or None if it has none.
43+
"""
44+
name = getattr(tz, "key", None) or getattr(tz, "zone", None)
45+
if isinstance(name, str):
46+
return name if _IANA_TIMEZONE_NAME.fullmatch(name) else None
47+
48+
if isinstance(tz, timezone):
49+
offset = tz.utcoffset(None)
50+
if offset % timedelta(hours=1):
51+
return None
52+
hours = offset // timedelta(hours=1)
53+
return "Etc/GMT%+d" % -hours if hours else "UTC"
54+
55+
return None

‎sentry_sdk/integrations/arq.py‎

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import sys
22
import time
3-
from datetime import timedelta, timezone
3+
from functools import wraps
44

55
import sentry_sdk
66
from sentry_sdk.consts import OP, SPANDATA, SPANSTATUS
77
from sentry_sdk.crons import monitor
8+
from sentry_sdk.crons.utils import _get_timezone_name
89
from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version
910
from sentry_sdk.integrations.logging import ignore_logger
1011
from sentry_sdk.scope import should_send_default_pii
@@ -221,6 +222,7 @@ def event_processor(event: "Event", hint: "Hint") -> "Optional[Event]":
221222

222223

223224
def _wrap_coroutine(name: str, coroutine: "WorkerCoroutine") -> "WorkerCoroutine":
225+
@wraps(coroutine)
224226
async def _sentry_coroutine(
225227
ctx: "Dict[Any, Any]", *args: "Any", **kwargs: "Any"
226228
) -> "Any":
@@ -326,6 +328,9 @@ def _monitor_cron_job(
326328
return
327329
cron_job._sentry_monitored = True
328330

331+
if getattr(cron_job.coroutine, "_sentry_monitored", False):
332+
return
333+
329334
# arq names cron jobs "cron:<function name>" by default.
330335
monitor_slug = cron_job.name
331336
if monitor_slug.startswith("cron:"):
@@ -393,35 +398,23 @@ def _get_crontab(cron_job: "CronJob") -> "Optional[str]":
393398
return " ".join(fields) # type: ignore[arg-type]
394399

395400

396-
def _get_timezone_name(worker: "Worker") -> "Optional[str]":
401+
def _get_worker_timezone_name(worker: "Worker") -> "Optional[str]":
397402
tz = getattr(worker, "timezone", None)
398403
if tz is None:
399404
# Before arq 0.25, cron jobs ran in naive local time.
400405
if time.timezone == 0 and (not time.daylight or time.altzone == 0):
401406
return "UTC"
402407
return None
403408

404-
# zoneinfo and pytz
405-
name = getattr(tz, "key", None) or getattr(tz, "zone", None)
406-
if isinstance(name, str):
407-
return name
408-
409409
# arq defaults to the system's fixed UTC offset at startup.
410-
if isinstance(tz, timezone):
411-
offset = tz.utcoffset(None)
412-
if offset % timedelta(hours=1):
413-
return None
414-
hours = offset // timedelta(hours=1)
415-
return "Etc/GMT%+d" % -hours if hours else "UTC"
416-
417-
return None
410+
return _get_timezone_name(tz)
418411

419412

420413
def _get_monitor_config(
421414
cron_job: "CronJob", worker: "Worker"
422415
) -> "Optional[MonitorConfig]":
423416
crontab = _get_crontab(cron_job)
424-
timezone_name = _get_timezone_name(worker)
417+
timezone_name = _get_worker_timezone_name(worker)
425418
if crontab is None or timezone_name is None:
426419
return None
427420
return {

‎tests/integrations/arq/test_arq_crons.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from arq.connections import ArqRedis
88
from fakeredis.aioredis import FakeRedis
99

10+
import sentry_sdk
1011
from sentry_sdk.integrations.arq import ArqIntegration, _get_monitor_config
1112

1213
try:
@@ -183,6 +184,25 @@ async def test_cron_job_monitored_once(sentry_init, capture_envelopes):
183184
assert statuses[:4] == ["in_progress", "ok", "in_progress", "ok"]
184185

185186

187+
@sentry_sdk.monitor(monitor_slug="decorated")
188+
async def decorated_job(ctx):
189+
pass
190+
191+
192+
@pytest.mark.asyncio
193+
async def test_monitor_decorated_cron_job_reports_once(sentry_init, capture_envelopes):
194+
sentry_init(integrations=[ArqIntegration(monitor_cron_jobs=True)])
195+
envelopes = capture_envelopes()
196+
197+
await _run_cron_jobs(
198+
cron(decorated_job, run_at_startup=True), timezone=timezone.utc
199+
)
200+
201+
check_ins = _check_ins(envelopes)
202+
assert {c["monitor_slug"] for c in check_ins} == {"decorated"}
203+
assert [c["status"] for c in check_ins[:2]] == ["in_progress", "ok"]
204+
205+
186206
class _Worker:
187207
def __init__(self, timezone):
188208
self.timezone = timezone

0 commit comments

Comments
 (0)