|
| 1 | +"""Shared internals for taskbadger's optional system integrations |
| 2 | +(Celery, Procrastinate). Not part of the public API. |
| 3 | +
|
| 4 | +Each integration creates its own module-level ``TaskCache`` instance and |
| 5 | +defines a thin ``safe_get_task`` wrapper that reads ``get_task`` from the |
| 6 | +integration module's own globals (so existing test mocks on |
| 7 | +``taskbadger.celery.get_task`` / ``taskbadger.procrastinate.get_task`` keep |
| 8 | +working). ``BaseSystemIntegration`` provides the common ctor/include-exclude |
| 9 | +shape; subclasses override ``track_task`` if they need to filter additional |
| 10 | +task names (e.g. Procrastinate built-ins). |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import collections |
| 16 | +import logging |
| 17 | +import re |
| 18 | +from collections.abc import Callable |
| 19 | + |
| 20 | +from .internal.models import StatusEnum |
| 21 | +from .systems import System |
| 22 | + |
| 23 | +log = logging.getLogger("taskbadger") |
| 24 | + |
| 25 | +TERMINAL_STATES = { |
| 26 | + StatusEnum.SUCCESS, |
| 27 | + StatusEnum.ERROR, |
| 28 | + StatusEnum.CANCELLED, |
| 29 | + StatusEnum.STALE, |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +class TaskCache: |
| 34 | + """Bounded LRU-ish cache for TaskBadger Task objects. |
| 35 | +
|
| 36 | + Keys are arbitrary hashable values chosen by the caller (typically the |
| 37 | + task id). Auto-prunes on ``set`` when ``maxsize`` is exceeded. |
| 38 | + """ |
| 39 | + |
| 40 | + def __init__(self, maxsize: int = 128): |
| 41 | + self.cache: collections.OrderedDict = collections.OrderedDict() |
| 42 | + self.maxsize = maxsize |
| 43 | + |
| 44 | + def set(self, key, value) -> None: |
| 45 | + self.cache[key] = value |
| 46 | + if len(self.cache) > self.maxsize: |
| 47 | + self.cache.popitem(last=False) |
| 48 | + |
| 49 | + def get(self, key): |
| 50 | + return self.cache.get(key) |
| 51 | + |
| 52 | + def unset(self, key) -> None: |
| 53 | + self.cache.pop(key, None) |
| 54 | + |
| 55 | + |
| 56 | +def safe_get_task(cache: TaskCache, task_id: str, get_task_fn: Callable): |
| 57 | + """Cache-aware ``get_task``: returns the cached entry if present, otherwise |
| 58 | + fetches via ``get_task_fn`` and caches the result. Errors are logged and |
| 59 | + swallowed (returns ``None``). ``None`` results are not cached. |
| 60 | +
|
| 61 | + ``get_task_fn`` is passed in (rather than imported here) so callers can |
| 62 | + use their own module-level ``get_task`` reference — this keeps existing |
| 63 | + test patches on ``taskbadger.celery.get_task`` / ``taskbadger.procrastinate.get_task`` |
| 64 | + intercepting the fetch. |
| 65 | + """ |
| 66 | + cached = cache.get(task_id) |
| 67 | + if cached is not None: |
| 68 | + return cached |
| 69 | + try: |
| 70 | + task = get_task_fn(task_id) |
| 71 | + except Exception as e: |
| 72 | + log.warning("Error fetching task '%s': %s", task_id, e) |
| 73 | + return None |
| 74 | + cache.set(task_id, task) |
| 75 | + return task |
| 76 | + |
| 77 | + |
| 78 | +def match_task_name(task_name: str, includes, excludes) -> bool: |
| 79 | + """Return True if ``task_name`` should be tracked under the given rules. |
| 80 | +
|
| 81 | + Excludes win over includes. Both lists contain regex strings matched with |
| 82 | + ``re.fullmatch``. ``None`` means "no rule". |
| 83 | + """ |
| 84 | + if excludes: |
| 85 | + for exclude in excludes: |
| 86 | + if re.fullmatch(exclude, task_name): |
| 87 | + return False |
| 88 | + |
| 89 | + if includes: |
| 90 | + for include in includes: |
| 91 | + if re.fullmatch(include, task_name): |
| 92 | + return True |
| 93 | + return False |
| 94 | + |
| 95 | + return True |
| 96 | + |
| 97 | + |
| 98 | +class BaseSystemIntegration(System): |
| 99 | + """Common ctor + ``track_task`` body for system integrations. |
| 100 | +
|
| 101 | + Subclasses set ``identifier`` and may override ``track_task`` to add |
| 102 | + additional filtering (e.g. skipping built-in tasks). |
| 103 | + """ |
| 104 | + |
| 105 | + def __init__(self, auto_track_tasks=True, includes=None, excludes=None, record_task_args=False): |
| 106 | + self.auto_track_tasks = auto_track_tasks |
| 107 | + self.includes = includes |
| 108 | + self.excludes = excludes |
| 109 | + self.record_task_args = record_task_args |
| 110 | + |
| 111 | + def track_task(self, task_name: str) -> bool: |
| 112 | + if not self.auto_track_tasks: |
| 113 | + return False |
| 114 | + return match_task_name(task_name, self.includes, self.excludes) |
0 commit comments