jobs_time.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """Per-job ``timezone`` and ``grace_minutes`` knobs (sibling of ``cron/jobs.py``).
  2. A job may pin its own IANA ``timezone``: its cron expression is then that zone's WALL CLOCK,
  3. independent of the profile's configured zone. Absent/None means "inherit the profile", so a
  4. store written before this field existed keeps byte-identical behaviour. ``grace_minutes``
  5. overrides the computed half-period catch-up window for one job (``0`` = never catch up).
  6. Behaviour lives here, not in the facade: ``cron/jobs.py`` is already past the file-lines
  7. ratchet. The facade keeps the call sites (``compute_next_run``, the due scan, and every write
  8. site that advances ``next_run_at``), which read the pins through this module.
  9. Why the due scan needs the pin too: ``_ensure_aware`` normalizes a stored instant into a zone,
  10. and the cron repair predicates then compare WALL CLOCKS. Normalizing a New-York job's instant
  11. into a Los-Angeles profile zone makes the wall clock look like it is still in the future, so
  12. ``_repair_timezone_shifted_cron`` re-anchors to the NEXT occurrence and the due one is lost —
  13. the "job timezone east of the profile timezone silently never fires" failure. See
  14. ``cron.jobs._evaluate_due_job``.
  15. """
  16. from __future__ import annotations
  17. import logging
  18. from datetime import datetime
  19. from typing import Any, Optional
  20. from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
  21. logger = logging.getLogger(__name__)
  22. TIMEZONE_KEY = "timezone"
  23. GRACE_KEY = "grace_minutes"
  24. # ``0`` is a real value ("skip a missed occurrence instead of running it late"); a whole day is
  25. # the most a late run can usefully be.
  26. MIN_GRACE_MINUTES = 0
  27. MAX_GRACE_MINUTES = 24 * 60
  28. # A corrupt persisted value would otherwise log on every 60s scan. Warn once per distinct value.
  29. _warned: set[str] = set()
  30. def reset_warning_state() -> None:
  31. """Forget which corrupt values were already warned about (tests, config reloads)."""
  32. _warned.clear()
  33. def _warn_once(kind: str, value: Any, detail: str) -> None:
  34. key = f"{kind}:{value!r}"
  35. if key in _warned:
  36. return
  37. _warned.add(key)
  38. logger.warning(
  39. "Job %s %r is invalid (%s); falling back to the profile setting. Fix or clear it with "
  40. "`hermes cron edit`.", kind, value, detail)
  41. def normalize_timezone(value: Any) -> Optional[str]:
  42. """Validate a job's ``timezone`` and return the canonical IANA key.
  43. ``None``/``""`` mean "inherit the profile timezone", stored as an ABSENT key. Anything that
  44. is not a resolvable IANA zone raises ValueError BEFORE the record is written, so a typo can
  45. never reach the tick loop.
  46. """
  47. if value is None:
  48. return None
  49. if not isinstance(value, str):
  50. raise ValueError(
  51. "timezone must be an IANA name such as 'Asia/Hong_Kong', "
  52. f"not {type(value).__name__}.")
  53. name = value.strip()
  54. if not name:
  55. return None
  56. try:
  57. return ZoneInfo(name).key
  58. except (ZoneInfoNotFoundError, ValueError) as exc:
  59. raise ValueError(
  60. f"Unknown timezone {name!r}. Use an IANA key from "
  61. f"`zoneinfo.available_timezones()`, e.g. 'Asia/Hong_Kong'.") from exc
  62. def normalize_grace_minutes(value: Any) -> Optional[int]:
  63. """Validate a job's ``grace_minutes`` override; None means "use the computed window".
  64. ``0`` is a real value (never catch up), so it must never be collapsed into absent:
  65. ``0 == False`` in Python, which is exactly the trap the ``workdir`` update lambda
  66. (``v in {None, "", False}``) would spring. Bools are therefore rejected explicitly.
  67. """
  68. if value is None:
  69. return None
  70. if isinstance(value, bool):
  71. raise ValueError(
  72. "grace_minutes must be a whole number of minutes (0 = never catch up), "
  73. "not a boolean.")
  74. if isinstance(value, str):
  75. if not value.strip():
  76. return None
  77. if not value.strip().lstrip("+-").isdigit():
  78. raise ValueError(
  79. f"grace_minutes must be a whole number of minutes, not {value!r}.")
  80. try:
  81. minutes = int(value)
  82. except (TypeError, ValueError) as exc:
  83. raise ValueError(
  84. f"grace_minutes must be a whole number of minutes, not {value!r}.") from exc
  85. if isinstance(value, float) and value != minutes:
  86. raise ValueError(
  87. f"grace_minutes must be a whole number of minutes, not {value!r}.")
  88. if not MIN_GRACE_MINUTES <= minutes <= MAX_GRACE_MINUTES:
  89. raise ValueError(
  90. f"grace_minutes must be between {MIN_GRACE_MINUTES} and "
  91. f"{MAX_GRACE_MINUTES} (0 = never catch up), got {minutes}.")
  92. return minutes
  93. def zone_for_job(job_or_timezone: Any) -> Optional[ZoneInfo]:
  94. """The zone a job's schedule is expressed in, or None to inherit the profile's.
  95. Accepts a job record or a bare ``timezone`` value. Never raises: a corrupt stored value
  96. degrades to the profile zone (warned once per value) instead of breaking the tick it is
  97. read in — the 60s scan must not die on one bad record.
  98. """
  99. if isinstance(job_or_timezone, dict):
  100. value = job_or_timezone.get(TIMEZONE_KEY)
  101. else:
  102. value = job_or_timezone
  103. if not isinstance(value, str) or not value.strip():
  104. return None
  105. try:
  106. return ZoneInfo(value.strip())
  107. except (ZoneInfoNotFoundError, ValueError) as exc:
  108. _warn_once(TIMEZONE_KEY, value, str(exc))
  109. return None
  110. def grace_seconds_override(grace_minutes: Any) -> Optional[int]:
  111. """Catch-up window in seconds from an explicit override, or None to compute it from cadence.
  112. Tolerant read (the record may have been hand-edited): a bad value is ignored rather than
  113. crashing the scan.
  114. """
  115. try:
  116. minutes = normalize_grace_minutes(grace_minutes)
  117. except ValueError as exc:
  118. _warn_once(GRACE_KEY, grace_minutes, str(exc))
  119. return None
  120. return None if minutes is None else minutes * 60
  121. def prune_inherited_knobs(record: dict[str, Any]) -> None:
  122. """An explicitly cleared knob is stored by DROPPING the key, not as null: an absent optional
  123. key is this repo's spelling for "unset" (see ``cron/jobs.py``'s optional-field write loop),
  124. and a stored null would render as a pinned-but-blank zone.
  125. ``grace_minutes`` is tested with ``is None`` — ``0`` is the real "never catch up" value and
  126. must survive, which is exactly the ``0 == False`` trap an ``in {None, "", False}`` test
  127. would spring.
  128. """
  129. if TIMEZONE_KEY in record and not record.get(TIMEZONE_KEY):
  130. record.pop(TIMEZONE_KEY, None)
  131. if GRACE_KEY in record and record.get(GRACE_KEY) is None:
  132. record.pop(GRACE_KEY, None)
  133. def oneshot_instant(value: Any, zone: Optional[ZoneInfo] = None) -> Optional[datetime]:
  134. """Parse a one-shot ``run_at`` into an aware instant, or None when unparseable.
  135. An offset-bearing value is already an instant. An offset-LESS value is the job's own wall
  136. clock, so a pinned zone interprets it in that zone (``2026-06-01T09:00:00`` means 09:00
  137. for THIS job) instead of in the host's local time.
  138. """
  139. from cron.jobs import _ensure_aware # late import: the facade owns naive normalization
  140. try:
  141. dt = datetime.fromisoformat(str(value))
  142. except (TypeError, ValueError):
  143. return None
  144. if dt.tzinfo is None and zone is not None:
  145. return dt.replace(tzinfo=zone)
  146. return _ensure_aware(dt, zone)