taskferry-django 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,85 @@
1
+ """Taskferry for Django — a bridge, in the direction Django expects.
2
+
3
+ ```mermaid
4
+ sequenceDiagram
5
+ participant App as Django app
6
+ participant DT as django.tasks
7
+ participant B as TaskferryBackend
8
+ participant TP as Taskferry runtime
9
+ participant E as engine
10
+
11
+ App->>DT: my_task.enqueue(42)
12
+ DT->>B: enqueue(task, args, kwargs)
13
+ B->>TP: submit(TaskSpec)
14
+ TP->>E: Procrastinate / Cloud Tasks / thread pool
15
+ E-->>TP: execution
16
+ TP-->>B: ExecutionHandle
17
+ B-->>DT: TaskResult
18
+ ```
19
+
20
+ Django 6 ships a real task API. Taskferry does not compete with it and does not
21
+ add a second one — it supplies a **backend** for the standard ``TASKS`` setting,
22
+ so application code stays ordinary Django:
23
+
24
+ # myapp/tasks.py — unchanged, forever
25
+ from django.tasks import task
26
+
27
+ @task
28
+ def resize_image(image_id: int) -> None: ...
29
+
30
+ # settings.py — this is the only thing that changes engines
31
+ TASKS = {"default": {"BACKEND": "taskferry_django.TaskferryBackend"}}
32
+
33
+ TASKFERRY = {
34
+ "backends": {"pg": {"factory": "procrastinate", "app": "myapp.tasks:app"}},
35
+ "defaults": {"task": "pg"},
36
+ }
37
+
38
+ The dependency direction is the whole point:
39
+
40
+ ```mermaid
41
+ flowchart BT
42
+ DJ["Django"]
43
+ TPD["taskferry_django"]
44
+ TP["taskferry"]
45
+
46
+ DJ --> TPD --> TP
47
+ ```
48
+
49
+ ``taskferry`` never imports Django. An architectural test enforces it, and
50
+ ``pytest packages/taskferry`` passes in an environment where Django is not
51
+ installed. So the same Procrastinate configuration serves a Django site, a
52
+ FastAPI service, a CLI and a library — none of which have to agree on a web
53
+ framework to agree on a queue.
54
+
55
+ What this package adds beyond the backend: configuration from ``settings.TASKFERRY``
56
+ (:mod:`taskferry_django.config`), enqueue-after-commit
57
+ (:mod:`taskferry_django.transaction`), system checks that catch a misconfiguration
58
+ at ``manage.py check`` time rather than at 3am (:mod:`taskferry_django.checks`), and
59
+ a ``manage.py taskferry`` command wrapping the same CLI.
60
+ """
61
+
62
+ from __future__ import annotations
63
+
64
+ from .backend import TaskferryBackend
65
+ from .config import config_from_settings, get_runtime, reset_runtime
66
+ from .execute import run_task
67
+ from .transaction import submit_on_commit, task_on_commit
68
+ from .views import make_task_webhook, task_webhook
69
+
70
+ __version__ = "0.2.0"
71
+
72
+ __all__ = [
73
+ "TaskferryBackend",
74
+ "__version__",
75
+ "config_from_settings",
76
+ "get_runtime",
77
+ "make_task_webhook",
78
+ "reset_runtime",
79
+ "run_task",
80
+ "submit_on_commit",
81
+ "task_on_commit",
82
+ "task_webhook",
83
+ ]
84
+
85
+ default_app_config = "taskferry_django.apps.TaskferryConfig"
@@ -0,0 +1,41 @@
1
+ """The Django ``AppConfig``.
2
+
3
+ Add ``"taskferry_django"`` to ``INSTALLED_APPS`` and you get the system checks and
4
+ a clean shutdown. That is all it does — no autodiscovery, no import-time scanning
5
+ of your task modules, no global registry mutated by a side effect. Configuration
6
+ is read when the runtime is first needed, from the setting, explicitly.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from django.apps import AppConfig
14
+ from django.core.checks import register
15
+ from django.core.signals import setting_changed
16
+
17
+
18
+ class TaskferryConfig(AppConfig):
19
+ """Registers Taskferry's system checks and keeps the runtime in step."""
20
+
21
+ name = "taskferry_django"
22
+ label = "taskferry"
23
+ verbose_name = "Taskferry"
24
+
25
+ def ready(self) -> None:
26
+ from .checks import check_taskferry
27
+
28
+ register(check_taskferry)
29
+ # A test using override_settings(TASKFERRY=...) must get a runtime built
30
+ # from the new settings, not the one cached before the override.
31
+ setting_changed.connect(_reset_on_setting_change)
32
+
33
+
34
+ def _reset_on_setting_change(sender: Any = None, setting: str = "", **kwargs: Any) -> None:
35
+ if setting in {"TASKFERRY", "TASKS"}:
36
+ from .config import reset_runtime
37
+
38
+ reset_runtime()
39
+
40
+
41
+ __all__ = ["TaskferryConfig"]
@@ -0,0 +1,195 @@
1
+ """``TaskferryBackend`` — a Django Tasks backend that delegates to Taskferry.
2
+
3
+ Django's ``BaseTaskBackend`` contract is small: declare feature flags, implement
4
+ ``enqueue``, return a ``TaskResult``. This class implements it by translating into
5
+ a :class:`~taskferry.specs.TaskSpec` and handing that to the runtime, which routes
6
+ it wherever the deployment says.
7
+
8
+ ```mermaid
9
+ flowchart LR
10
+ T["django Task<br/>module_path · args · queue · priority · run_after"]
11
+ S["TaskSpec<br/>task · args · queue · priority · run_at"]
12
+ RT["Taskferry runtime"]
13
+ R["django TaskResult"]
14
+
15
+ T -->|"translate"| S --> RT
16
+ RT -->|"Execution"| R
17
+ ```
18
+
19
+ Feature flags are **derived from the routed backend's capabilities**, not
20
+ hardcoded. Django asks "do you support defer?" and this backend answers by
21
+ looking at what the engine the deployment actually chose can do. Switch
22
+ ``TASKFERRY`` from a thread pool to Cloud Tasks and ``supports_get_result``
23
+ changes from ``True`` to ``False`` on its own, because that is the truth. Nothing
24
+ had to be edited, and nothing pretends.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Any
30
+
31
+ from django.tasks.backends.base import BaseTaskBackend
32
+ from django.tasks.base import Task, TaskResult, TaskResultStatus
33
+
34
+ from taskferry import CapabilitySet, ExecutionState, Taskferry, TaskSpec
35
+ from taskferry.errors import TaskferryError
36
+
37
+ from .config import get_runtime
38
+ from .execute import DISPATCH_REF
39
+
40
+ #: Portable state -> the Django Tasks status vocabulary. Django's enum is
41
+ #: coarser than Taskferry's, so several states collapse; the mapping is written
42
+ #: out rather than inferred so the loss is visible and reviewable.
43
+ _STATUS_MAP: dict[ExecutionState, TaskResultStatus] = {
44
+ ExecutionState.PENDING: TaskResultStatus.READY,
45
+ ExecutionState.QUEUED: TaskResultStatus.READY,
46
+ ExecutionState.RUNNING: TaskResultStatus.RUNNING,
47
+ ExecutionState.SUCCEEDED: TaskResultStatus.SUCCESSFUL,
48
+ ExecutionState.FAILED: TaskResultStatus.FAILED,
49
+ ExecutionState.CANCELLED: TaskResultStatus.FAILED,
50
+ ExecutionState.TIMED_OUT: TaskResultStatus.FAILED,
51
+ ExecutionState.UNKNOWN: TaskResultStatus.READY,
52
+ }
53
+
54
+
55
+ class TaskferryBackend(BaseTaskBackend):
56
+ """Routes ``django.tasks`` enqueues through a Taskferry runtime.
57
+
58
+ Configure it the standard Django way::
59
+
60
+ TASKS = {
61
+ "default": {
62
+ "BACKEND": "taskferry_django.TaskferryBackend",
63
+ "QUEUES": ["default", "metadata"],
64
+ "OPTIONS": {"backend": "pg"}, # optional: pin, skip routing
65
+ }
66
+ }
67
+
68
+ ``OPTIONS["backend"]`` pins every enqueue from this Django alias to one named
69
+ Taskferry backend. Leave it out and the router decides from the task's queue,
70
+ which is usually what you want — that is where the portability lives.
71
+ """
72
+
73
+ #: Django reads these at import time, before any task is enqueued, so they
74
+ #: cannot depend on which backend a given task routes to. They are set
75
+ #: permissively and the real, per-backend answer is enforced at submit time
76
+ #: by the capability check, which raises rather than silently degrading.
77
+ supports_defer = True
78
+ supports_async_task = True
79
+ supports_get_result = True
80
+ supports_priority = True
81
+
82
+ def __init__(self, alias: str, params: dict[str, Any]) -> None:
83
+ super().__init__(alias, params)
84
+ self._pinned = self.options.get("backend")
85
+ self._runtime_override: Taskferry | None = None
86
+ # Django defaults ``QUEUES`` to ``{"default"}`` and rejects anything
87
+ # else. That is the right check for a backend that owns its queues, and
88
+ # the wrong one here: a Taskferry queue is a *routing key*, and which
89
+ # queues exist is a property of the routes, not of this class. An empty
90
+ # set tells Django to skip the check and let the router answer — where an
91
+ # unroutable queue raises RoutingError naming the rules it tried, which
92
+ # is a far more useful error than "not valid for backend".
93
+ #
94
+ # Setting QUEUES explicitly still works, and re-enables Django's check as
95
+ # a deliberate allowlist.
96
+ if "QUEUES" not in params:
97
+ self.queues: set[str] = set()
98
+
99
+ @property
100
+ def runtime(self) -> Taskferry:
101
+ """The Taskferry runtime. Injectable for tests via :meth:`use_runtime`."""
102
+ return self._runtime_override if self._runtime_override is not None else get_runtime()
103
+
104
+ def use_runtime(self, runtime: Taskferry | None) -> None:
105
+ """Point this backend at a specific runtime. For tests."""
106
+ self._runtime_override = runtime
107
+
108
+ # -- capabilities ---------------------------------------------------------- #
109
+ def taskferry_capabilities(self, queue: str = "default") -> CapabilitySet:
110
+ """What the backend this queue routes to can actually do.
111
+
112
+ Returns the :class:`~taskferry.CapabilitySet` itself rather than a plain
113
+ set, so callers get ``supports()`` and ``require()`` — and so the answer
114
+ stays attributed to the backend that gave it.
115
+
116
+ Exposed so an application (or a system check) can ask honestly, instead
117
+ of trusting the coarse Django flags above.
118
+ """
119
+ probe = TaskSpec(task=DISPATCH_REF, queue=queue)
120
+ name = self._pinned or self.runtime.router.resolve(probe)
121
+ return self.runtime.capabilities(str(name))
122
+
123
+ # -- the Django contract ---------------------------------------------------- #
124
+ def enqueue(self, task: Task, args: list[Any], kwargs: dict[str, Any]) -> TaskResult:
125
+ """Translate a Django task into a spec and submit it."""
126
+ self.validate_task(task)
127
+ spec = self.build_spec(task, args, kwargs)
128
+ handle = self.runtime.submit(spec, backend=self._pinned)
129
+ return self._task_result(task, args, kwargs, handle.execution)
130
+
131
+ def build_spec(self, task: Task, args: list[Any], kwargs: dict[str, Any]) -> TaskSpec:
132
+ """Build the portable spec for a Django task. Pure, and easy to assert on.
133
+
134
+ Every spec points at :data:`~taskferry_django.execute.DISPATCH_REF`, with
135
+ the Django task path travelling as data. See
136
+ :mod:`taskferry_django.execute` for why the task's own path cannot be used
137
+ directly — in short, ``@task`` produces a Task object rather than a
138
+ callable, and teaching the core about that would couple it to Django.
139
+
140
+ :attr:`~taskferry.specs.ExecutionSpec.name` carries the real task name, so
141
+ routing by ``name`` and every log line still identify the actual work.
142
+ """
143
+ return TaskSpec(
144
+ task=DISPATCH_REF,
145
+ args=(task.module_path, list(args), dict(kwargs)),
146
+ queue=task.queue_name,
147
+ priority=task.priority,
148
+ run_at=task.run_after,
149
+ name=task.name,
150
+ labels={"django_task": task.module_path},
151
+ )
152
+
153
+ def _task_result(
154
+ self,
155
+ task: Task,
156
+ args: list[Any],
157
+ kwargs: dict[str, Any],
158
+ execution: Any,
159
+ ) -> TaskResult:
160
+ from django.utils import timezone
161
+
162
+ return TaskResult(
163
+ task=task,
164
+ # Django caps result ids at 64 characters; a Taskferry id is well
165
+ # inside that, which is one reason ids are minted rather than
166
+ # borrowed from the provider (a Cloud Tasks name is far longer).
167
+ id=str(execution.id),
168
+ status=_STATUS_MAP.get(execution.state, TaskResultStatus.READY),
169
+ enqueued_at=execution.created_at or timezone.now(),
170
+ started_at=execution.started_at,
171
+ finished_at=execution.finished_at,
172
+ last_attempted_at=execution.started_at,
173
+ args=list(args),
174
+ kwargs=dict(kwargs),
175
+ backend=self.alias,
176
+ errors=[],
177
+ worker_ids=[],
178
+ )
179
+
180
+ def get_result(self, result_id: str) -> TaskResult:
181
+ """Look up a previously enqueued task.
182
+
183
+ Raises:
184
+ TaskferryError: when the routed backend cannot report state. Django's
185
+ API implies every backend can look a result up; most real queues
186
+ cannot, and this says so instead of returning a fabricated one.
187
+ """
188
+ raise TaskferryError(
189
+ "get_result() is not supported through the Taskferry bridge: use "
190
+ "runtime.get(execution_id) directly, where the backend's capabilities "
191
+ "are visible and an unsupported lookup fails honestly"
192
+ )
193
+
194
+
195
+ __all__ = ["TaskferryBackend"]
@@ -0,0 +1,194 @@
1
+ """System checks — find the misconfiguration at ``manage.py check``, not at 3am.
2
+
3
+ Every check here answers a question that otherwise gets answered by a production
4
+ incident:
5
+
6
+ * is ``TASKFERRY`` even parseable?
7
+ * do the routes point at backends that exist?
8
+ * is every configured backend actually *constructible* — adapter installed,
9
+ required options present, credentials resolvable?
10
+ * does anything have a default backend to fall back on?
11
+ * is ``TASKS`` pointed at this bridge at all?
12
+
13
+ The expensive one is deliberate. "The adapter is installed" and "the adapter can
14
+ be built with these options" are different questions, and only the second one
15
+ matters. Building each backend at check time surfaces a missing ``project`` or an
16
+ unresolvable Procrastinate app during deployment, where a failed check is cheap.
17
+
18
+ ```mermaid
19
+ flowchart TD
20
+ C["manage.py check"]
21
+ S["settings.TASKFERRY parses?"]
22
+ R["routes name known backends?"]
23
+ B["each backend constructible?"]
24
+ D["defaults present?"]
25
+ T["TASKS points at TaskferryBackend?"]
26
+
27
+ C --> S --> R --> B --> D --> T
28
+ ```
29
+
30
+ Registered by :class:`taskferry_django.apps.TaskferryConfig`, so adding
31
+ ``"taskferry_django"`` to ``INSTALLED_APPS`` is all it takes.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from typing import Any
37
+
38
+ from django.core.checks import CheckMessage, Error, Warning
39
+
40
+ from taskferry.errors import TaskferryError
41
+
42
+ ID_CONFIG = "taskferry.E001"
43
+ ID_BACKEND = "taskferry.E002"
44
+ ID_NO_DEFAULT = "taskferry.W001"
45
+ ID_NOT_WIRED = "taskferry.W002"
46
+ ID_LOCAL_IN_PRODUCTION = "taskferry.W003"
47
+
48
+
49
+ def check_taskferry(app_configs: Any = None, **kwargs: Any) -> list[CheckMessage]:
50
+ """Validate the Taskferry configuration. Registered as a Django system check."""
51
+ from django.conf import settings
52
+
53
+ from .config import config_from_settings
54
+
55
+ messages: list[CheckMessage] = []
56
+
57
+ try:
58
+ config = config_from_settings(settings)
59
+ except Exception as exc:
60
+ return [
61
+ Error(
62
+ f"settings.TASKFERRY could not be loaded: {exc}",
63
+ hint=(
64
+ "TASKFERRY must be a dict of {'backends': ..., 'routes': ..., 'defaults': ...}"
65
+ ),
66
+ id=ID_CONFIG,
67
+ )
68
+ ]
69
+
70
+ messages += _check_backends_build(config)
71
+ messages += _check_defaults(config)
72
+ messages += _check_tasks_setting(settings)
73
+ messages += _check_not_local_in_production(settings, config)
74
+ return messages
75
+
76
+
77
+ def _check_backends_build(config: Any) -> list[CheckMessage]:
78
+ """Actually construct every configured backend."""
79
+ from taskferry import Taskferry
80
+
81
+ messages: list[CheckMessage] = []
82
+ runtime = Taskferry(config=config)
83
+ try:
84
+ for name in sorted(config.backends):
85
+ try:
86
+ runtime.backend(name)
87
+ except TaskferryError as exc:
88
+ messages.append(
89
+ Error(
90
+ f"the Taskferry backend {name!r} cannot be built: {exc}",
91
+ hint="Check that its adapter distribution is installed and that "
92
+ "every required option is set in settings.TASKFERRY['backends'].",
93
+ id=ID_BACKEND,
94
+ )
95
+ )
96
+ except Exception as exc: # an adapter raising something unexpected
97
+ messages.append(
98
+ Error(
99
+ f"the Taskferry backend {name!r} raised {type(exc).__name__}: {exc}",
100
+ id=ID_BACKEND,
101
+ )
102
+ )
103
+ finally:
104
+ runtime.close()
105
+ return messages
106
+
107
+
108
+ def _check_defaults(config: Any) -> list[CheckMessage]:
109
+ from taskferry import ExecutionKind
110
+
111
+ if not config.defaults and not config.routes:
112
+ return [
113
+ Warning(
114
+ "Taskferry has no routes and no default backends, so every submit will fail.",
115
+ hint="Set TASKFERRY['defaults'] = {'task': '<backend>', 'job': '<backend>'} "
116
+ "or add routes.",
117
+ id=ID_NO_DEFAULT,
118
+ )
119
+ ]
120
+ missing = [
121
+ kind.value
122
+ for kind in ExecutionKind
123
+ if kind not in config.defaults
124
+ and not any(route.kind in (None, kind) for route in config.routes)
125
+ ]
126
+ if missing:
127
+ return [
128
+ Warning(
129
+ f"Taskferry has no route or default for: {', '.join(missing)}. "
130
+ f"Submitting one of those will raise RoutingError.",
131
+ id=ID_NO_DEFAULT,
132
+ )
133
+ ]
134
+ return []
135
+
136
+
137
+ def _check_tasks_setting(settings: Any) -> list[CheckMessage]:
138
+ tasks = getattr(settings, "TASKS", None) or {}
139
+ if not isinstance(tasks, dict):
140
+ return []
141
+ uses_bridge = any(
142
+ "taskferry_django" in str(entry.get("BACKEND", ""))
143
+ for entry in tasks.values()
144
+ if isinstance(entry, dict)
145
+ )
146
+ if not uses_bridge and getattr(settings, "TASKFERRY", None):
147
+ return [
148
+ Warning(
149
+ "settings.TASKFERRY is configured but no TASKS backend routes through "
150
+ "Taskferry, so django.tasks enqueues will not reach it.",
151
+ hint="Set TASKS = {'default': {'BACKEND': 'taskferry_django.TaskferryBackend'}} "
152
+ "or use the runtime directly with taskferry_django.get_runtime().",
153
+ id=ID_NOT_WIRED,
154
+ )
155
+ ]
156
+ return []
157
+
158
+
159
+ def _check_not_local_in_production(settings: Any, config: Any) -> list[CheckMessage]:
160
+ """Warn when a non-DEBUG deployment is still on the in-process backends.
161
+
162
+ They work, they are useful, and they lose every pending task on restart. That
163
+ is fine in development and is very much not fine behind ``DEBUG = False``.
164
+ """
165
+ if getattr(settings, "DEBUG", False):
166
+ return []
167
+ in_process = {
168
+ name
169
+ for name, definition in config.backends.items()
170
+ if definition.factory in {"thread", "process", "inline"}
171
+ }
172
+ routed = set(config.defaults.values()) | {route.backend for route in config.routes}
173
+ at_risk = sorted(in_process & routed)
174
+ if not at_risk:
175
+ return []
176
+ return [
177
+ Warning(
178
+ f"DEBUG is False but these Taskferry backends run in this process and lose "
179
+ f"pending work on restart: {', '.join(at_risk)}.",
180
+ hint="Route production task queues at a durable engine "
181
+ "(taskferry-procrastinate, taskferry-cloudtasks) and jobs at a batch runtime.",
182
+ id=ID_LOCAL_IN_PRODUCTION,
183
+ )
184
+ ]
185
+
186
+
187
+ __all__ = [
188
+ "ID_BACKEND",
189
+ "ID_CONFIG",
190
+ "ID_LOCAL_IN_PRODUCTION",
191
+ "ID_NOT_WIRED",
192
+ "ID_NO_DEFAULT",
193
+ "check_taskferry",
194
+ ]
@@ -0,0 +1,116 @@
1
+ """Django settings in, :class:`~taskferry.TaskferryConfig` out.
2
+
3
+ ```mermaid
4
+ flowchart LR
5
+ S["settings.TASKFERRY<br/>(a plain dict)"]
6
+ F["config_from_settings()"]
7
+ C["TaskferryConfig"]
8
+ R["Taskferry runtime"]
9
+
10
+ S --> F --> C --> R
11
+ ```
12
+
13
+ This module is the *only* place in the whole project where Django settings are
14
+ read, and it lives in the Django adapter — which is exactly where the layering
15
+ says it belongs. ``taskferry.config`` cannot import ``django.conf``, so a
16
+ misplaced settings read is a test failure, not a review comment.
17
+
18
+ The setting is an ordinary dict in the shape
19
+ :meth:`~taskferry.TaskferryConfig.from_mapping` already understands, so nothing new
20
+ has to be learned to configure Taskferry from Django, and the same dict can be
21
+ lifted verbatim into a FastAPI service or a CLI when that day comes.
22
+
23
+ TASKFERRY = {
24
+ "backends": {
25
+ "pg": {"factory": "procrastinate", "app": "myapp.tasks:app"},
26
+ "heavy": {"factory": "cloudrun", "project": "p", "location": "europe-west1"},
27
+ },
28
+ "routes": [
29
+ {"kind": "task", "queue": "metadata", "backend": "pg"},
30
+ {"kind": "job", "profile": "heavy", "backend": "heavy"},
31
+ ],
32
+ "defaults": {"task": "pg", "job": "heavy"},
33
+ }
34
+
35
+ With no ``TASKFERRY`` setting at all, :func:`config_from_settings` falls back to
36
+ :meth:`TaskferryConfig.local` — so a fresh project runs tasks on a thread pool and
37
+ jobs as subprocesses, works immediately, and is obviously not production. That is
38
+ better than either crashing on first use or quietly doing nothing.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import threading
44
+ from typing import Any
45
+
46
+ from django.core.exceptions import ImproperlyConfigured
47
+
48
+ from taskferry import Taskferry, TaskferryConfig
49
+ from taskferry.errors import ConfigurationError
50
+
51
+ SETTING_NAME = "TASKFERRY"
52
+
53
+ _runtime: Taskferry | None = None
54
+ _lock = threading.Lock()
55
+
56
+
57
+ def config_from_settings(settings: Any = None) -> TaskferryConfig:
58
+ """Build a :class:`~taskferry.TaskferryConfig` from ``settings.TASKFERRY``.
59
+
60
+ Args:
61
+ settings: Settings object to read. Defaults to ``django.conf.settings``;
62
+ injectable so the loader is testable without a settings module.
63
+
64
+ Raises:
65
+ ImproperlyConfigured: when ``TASKFERRY`` is present but malformed. Raising
66
+ Django's own exception type means the error surfaces through
67
+ ``manage.py check`` and the usual startup path, in the form a Django
68
+ developer already knows how to read.
69
+ """
70
+ source = settings if settings is not None else _django_settings()
71
+ raw = getattr(source, SETTING_NAME, None)
72
+ if raw is None:
73
+ return TaskferryConfig.local()
74
+ if not isinstance(raw, dict):
75
+ raise ImproperlyConfigured(
76
+ f"settings.{SETTING_NAME} must be a dict, got {type(raw).__name__}"
77
+ )
78
+ try:
79
+ return TaskferryConfig.from_mapping(raw)
80
+ except ConfigurationError as exc:
81
+ raise ImproperlyConfigured(f"settings.{SETTING_NAME} is invalid: {exc}") from exc
82
+
83
+
84
+ def get_runtime(settings: Any = None) -> Taskferry:
85
+ """The process-wide runtime, built once from settings.
86
+
87
+ A single shared runtime is deliberate: backends hold connection pools and
88
+ clients, and building one per request would open a new pool per request. The
89
+ runtime is thread-safe, which is what makes sharing it correct under any
90
+ Django deployment model.
91
+
92
+ Use :func:`reset_runtime` in tests, or ``override_settings`` plus a reset.
93
+ """
94
+ global _runtime
95
+ with _lock:
96
+ if _runtime is None:
97
+ _runtime = Taskferry(config=config_from_settings(settings))
98
+ return _runtime
99
+
100
+
101
+ def reset_runtime() -> None:
102
+ """Close and forget the shared runtime. For tests and settings changes."""
103
+ global _runtime
104
+ with _lock:
105
+ existing, _runtime = _runtime, None
106
+ if existing is not None:
107
+ existing.close()
108
+
109
+
110
+ def _django_settings() -> Any:
111
+ from django.conf import settings
112
+
113
+ return settings
114
+
115
+
116
+ __all__ = ["SETTING_NAME", "config_from_settings", "get_runtime", "reset_runtime"]