django-redline 0.2.0a1__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.
- django_redline/__init__.py +23 -0
- django_redline/_drf.py +82 -0
- django_redline/apps.py +30 -0
- django_redline/checks.py +142 -0
- django_redline/conf.py +182 -0
- django_redline/explain.py +52 -0
- django_redline/instrument.py +557 -0
- django_redline/management/__init__.py +0 -0
- django_redline/management/commands/__init__.py +0 -0
- django_redline/management/commands/redline_clear.py +31 -0
- django_redline/management/commands/redline_prune.py +38 -0
- django_redline/management/commands/redline_scan.py +58 -0
- django_redline/management/commands/redline_scenario.py +135 -0
- django_redline/middleware.py +337 -0
- django_redline/py.typed +0 -0
- django_redline/runtime.py +141 -0
- django_redline/scan.py +336 -0
- django_redline/suggest.py +1121 -0
- django_redline/transactions.py +81 -0
- django_redline/urls.py +20 -0
- django_redline/views.py +325 -0
- django_redline-0.2.0a1.dist-info/METADATA +229 -0
- django_redline-0.2.0a1.dist-info/RECORD +25 -0
- django_redline-0.2.0a1.dist-info/WHEEL +4 -0
- django_redline-0.2.0a1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""django-redline: the Django adapter for Redline.
|
|
2
|
+
|
|
3
|
+
Add ``"django_redline"`` to ``INSTALLED_APPS``, ``"django_redline.middleware.RedlineMiddleware"``
|
|
4
|
+
near the top of ``MIDDLEWARE`` and ``path("redline/", include("django_redline.urls"))`` to
|
|
5
|
+
your URLconf. Every request is then recorded – SQL, cache and template spans, N+1 and
|
|
6
|
+
duplicate-query issues with ``select_related``/``prefetch_related`` fix diffs, one-click
|
|
7
|
+
EXPLAIN and opt-in flamegraphs – and browsable at ``/redline/``.
|
|
8
|
+
|
|
9
|
+
User code can time its own blocks with :func:`span` (re-exported from ``redline_core``)::
|
|
10
|
+
|
|
11
|
+
from django_redline import span
|
|
12
|
+
|
|
13
|
+
@span("pricing.compute")
|
|
14
|
+
def compute_price(order): ...
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from redline_core import span
|
|
20
|
+
|
|
21
|
+
__version__ = "0.2.0a1"
|
|
22
|
+
|
|
23
|
+
__all__ = ["__version__", "span"]
|
django_redline/_drf.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Django REST framework serialization as ``serializer`` spans.
|
|
2
|
+
|
|
3
|
+
``BaseSerializer.data`` is where DRF turns an instance (or queryset) into primitives, for
|
|
4
|
+
``Serializer``, ``ModelSerializer`` and ``ListSerializer`` alike (their ``data`` properties
|
|
5
|
+
call it through ``super()``), so that one property is wrapped. Only the *outermost* access
|
|
6
|
+
is recorded: nested serializers run inside their parent's ``to_representation`` and
|
|
7
|
+
serializers built by hand inside a ``SerializerMethodField`` are covered by the parent's
|
|
8
|
+
span. DRF is optional – without it nothing happens – and outside a traced request the
|
|
9
|
+
wrapper costs one ``ContextVar.get()``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import time
|
|
15
|
+
from contextvars import ContextVar
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from redline_core import record_span
|
|
19
|
+
from redline_core.recorder import current
|
|
20
|
+
|
|
21
|
+
__all__ = ["install_drf", "uninstall_drf"]
|
|
22
|
+
|
|
23
|
+
_perf = time.perf_counter
|
|
24
|
+
_original: list[Any] = []
|
|
25
|
+
_inside: ContextVar[bool] = ContextVar("redline_drf", default=False)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def install_drf() -> bool:
|
|
29
|
+
"""Patch ``BaseSerializer.data``; ``False`` when DRF is not installed. Idempotent."""
|
|
30
|
+
from django.apps import apps
|
|
31
|
+
|
|
32
|
+
if not apps.is_installed("rest_framework"):
|
|
33
|
+
return False
|
|
34
|
+
try:
|
|
35
|
+
from rest_framework.serializers import BaseSerializer
|
|
36
|
+
except ImportError:
|
|
37
|
+
return False
|
|
38
|
+
if _original:
|
|
39
|
+
return True
|
|
40
|
+
prop = BaseSerializer.__dict__["data"]
|
|
41
|
+
fget = prop.fget
|
|
42
|
+
_original.append(prop)
|
|
43
|
+
|
|
44
|
+
def data(self: Any) -> Any:
|
|
45
|
+
if _inside.get() or current() is None:
|
|
46
|
+
return fget(self)
|
|
47
|
+
token = _inside.set(True)
|
|
48
|
+
start = _perf()
|
|
49
|
+
result = None
|
|
50
|
+
try:
|
|
51
|
+
result = fget(self)
|
|
52
|
+
return result
|
|
53
|
+
finally:
|
|
54
|
+
_inside.reset(token)
|
|
55
|
+
duration = _perf() - start
|
|
56
|
+
many = hasattr(self, "child")
|
|
57
|
+
name = type(self.child if many else self).__name__
|
|
58
|
+
items = None
|
|
59
|
+
if many and result is not None:
|
|
60
|
+
try:
|
|
61
|
+
items = len(result)
|
|
62
|
+
except TypeError:
|
|
63
|
+
items = None
|
|
64
|
+
record_span(
|
|
65
|
+
"serializer",
|
|
66
|
+
f"{name}.data",
|
|
67
|
+
start,
|
|
68
|
+
duration,
|
|
69
|
+
{"library": "drf", "serializer": name, "items": items, "many": many},
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
BaseSerializer.data = property(data, prop.fset, prop.fdel, prop.__doc__) # type: ignore[assignment]
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def uninstall_drf() -> None:
|
|
77
|
+
"""Undo :func:`install_drf`."""
|
|
78
|
+
if not _original:
|
|
79
|
+
return
|
|
80
|
+
from rest_framework.serializers import BaseSerializer
|
|
81
|
+
|
|
82
|
+
BaseSerializer.data = _original.pop() # type: ignore[assignment]
|
django_redline/apps.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from django.apps import AppConfig
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class RedlineConfig(AppConfig):
|
|
9
|
+
name = "django_redline"
|
|
10
|
+
label = "django_redline"
|
|
11
|
+
verbose_name = "Redline"
|
|
12
|
+
|
|
13
|
+
def ready(self) -> None:
|
|
14
|
+
from django.core.signals import setting_changed
|
|
15
|
+
|
|
16
|
+
from . import (
|
|
17
|
+
checks, # noqa: F401 (registers the system checks)
|
|
18
|
+
runtime, # noqa: F401 (rebuilds the runtime on REDLINE changes)
|
|
19
|
+
)
|
|
20
|
+
from .instrument import install
|
|
21
|
+
|
|
22
|
+
install()
|
|
23
|
+
setting_changed.connect(_reset_on_urlconf, dispatch_uid="django_redline.urlconf")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _reset_on_urlconf(setting: str, **kwargs: Any) -> None:
|
|
27
|
+
if setting == "ROOT_URLCONF":
|
|
28
|
+
from .middleware import _reset_mount
|
|
29
|
+
|
|
30
|
+
_reset_mount()
|
django_redline/checks.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""System checks for a Redline installation.
|
|
2
|
+
|
|
3
|
+
======================== ==============================================================
|
|
4
|
+
id problem
|
|
5
|
+
======================== ==============================================================
|
|
6
|
+
``django_redline.E001`` ``REDLINE`` is invalid (unknown key, bad value, bad PERMISSION)
|
|
7
|
+
``django_redline.E002`` the storage directory cannot be created or is not writable
|
|
8
|
+
``django_redline.W001`` ``RedlineMiddleware`` is not in ``MIDDLEWARE``
|
|
9
|
+
``django_redline.W002`` ``GZipMiddleware`` runs inside Redline (bodies would be gzip)
|
|
10
|
+
``django_redline.W003`` ``RedlineMiddleware`` is listed after middleware it should time
|
|
11
|
+
``django_redline.W004`` ``django_redline.urls`` is not mounted, so the UI is unreachable
|
|
12
|
+
``django_redline.W005`` ``DEBUG`` is False and ``SAMPLE_RATE`` is 1.0 (every request)
|
|
13
|
+
======================== ==============================================================
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from django.conf import settings
|
|
22
|
+
from django.core.checks import Error, Tags, Warning, register
|
|
23
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
24
|
+
from django.urls import NoReverseMatch, reverse
|
|
25
|
+
|
|
26
|
+
from redline_core.access import Access
|
|
27
|
+
from redline_core.conf import SettingsError
|
|
28
|
+
|
|
29
|
+
from .conf import get_core_settings, get_options
|
|
30
|
+
|
|
31
|
+
MIDDLEWARE_PATH = "django_redline.middleware.RedlineMiddleware"
|
|
32
|
+
GZIP = "django.middleware.gzip.GZipMiddleware"
|
|
33
|
+
#: Middleware that should run *inside* Redline so their time is part of the trace.
|
|
34
|
+
SHOULD_FOLLOW = (
|
|
35
|
+
"django.contrib.sessions.middleware.SessionMiddleware",
|
|
36
|
+
"django.middleware.common.CommonMiddleware",
|
|
37
|
+
"django.middleware.csrf.CsrfViewMiddleware",
|
|
38
|
+
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
|
39
|
+
"django.contrib.messages.middleware.MessageMiddleware",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@register(Tags.compatibility)
|
|
44
|
+
def check_redline(app_configs: Any = None, **kwargs: Any) -> list:
|
|
45
|
+
try:
|
|
46
|
+
core = get_core_settings()
|
|
47
|
+
get_options()
|
|
48
|
+
Access(core) # a missing token_file, a weak token, a bad access_check path...
|
|
49
|
+
except SettingsError as exc:
|
|
50
|
+
return [Error(f"settings.REDLINE: {exc}", id="django_redline.E001")]
|
|
51
|
+
except ImproperlyConfigured as exc:
|
|
52
|
+
return [Error(str(exc), id="django_redline.E001")]
|
|
53
|
+
problems: list = []
|
|
54
|
+
problems += _middleware()
|
|
55
|
+
problems += _urls()
|
|
56
|
+
if core.enabled and not settings.DEBUG and core.sample_rate >= 1.0:
|
|
57
|
+
problems.append(
|
|
58
|
+
Warning(
|
|
59
|
+
"Redline records every request (SAMPLE_RATE = 1.0) while DEBUG is False.",
|
|
60
|
+
hint=(
|
|
61
|
+
"In production lower REDLINE['SAMPLE_RATE'] (e.g. 0.05); slow requests "
|
|
62
|
+
"and 5xx errors are always kept anyway. Leave SAMPLE_RATE unset to get "
|
|
63
|
+
"the production default of 0.1."
|
|
64
|
+
),
|
|
65
|
+
id="django_redline.W005",
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
if core.enabled:
|
|
69
|
+
problems += _storage(core.storage_path)
|
|
70
|
+
return problems
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _middleware() -> list:
|
|
74
|
+
middleware = list(getattr(settings, "MIDDLEWARE", None) or [])
|
|
75
|
+
if MIDDLEWARE_PATH not in middleware:
|
|
76
|
+
return [
|
|
77
|
+
Warning(
|
|
78
|
+
"RedlineMiddleware is not installed, so no request is recorded.",
|
|
79
|
+
hint=f"Add {MIDDLEWARE_PATH!r} near the top of MIDDLEWARE.",
|
|
80
|
+
id="django_redline.W001",
|
|
81
|
+
)
|
|
82
|
+
]
|
|
83
|
+
problems = []
|
|
84
|
+
position = middleware.index(MIDDLEWARE_PATH)
|
|
85
|
+
if GZIP in middleware[position + 1 :]:
|
|
86
|
+
problems.append(
|
|
87
|
+
Warning(
|
|
88
|
+
"GZipMiddleware is listed after RedlineMiddleware, so Redline sees "
|
|
89
|
+
"compressed response bodies.",
|
|
90
|
+
hint="Move RedlineMiddleware below GZipMiddleware.",
|
|
91
|
+
id="django_redline.W002",
|
|
92
|
+
)
|
|
93
|
+
)
|
|
94
|
+
before = [m for m in middleware[:position] if m in SHOULD_FOLLOW]
|
|
95
|
+
if before:
|
|
96
|
+
problems.append(
|
|
97
|
+
Warning(
|
|
98
|
+
"RedlineMiddleware is listed after " + ", ".join(before) + "; their time is "
|
|
99
|
+
"not part of the recorded requests.",
|
|
100
|
+
hint="Place RedlineMiddleware right after SecurityMiddleware/GZipMiddleware.",
|
|
101
|
+
id="django_redline.W003",
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
return problems
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _urls() -> list:
|
|
108
|
+
try:
|
|
109
|
+
reverse("redline:index")
|
|
110
|
+
except NoReverseMatch:
|
|
111
|
+
return [
|
|
112
|
+
Warning(
|
|
113
|
+
"Redline's URLs are not mounted, so the UI is unreachable.",
|
|
114
|
+
hint='Add path("redline/", include("django_redline.urls")) to your URLconf.',
|
|
115
|
+
id="django_redline.W004",
|
|
116
|
+
)
|
|
117
|
+
]
|
|
118
|
+
except Exception: # a broken URLconf is reported by Django's own checks
|
|
119
|
+
return []
|
|
120
|
+
return []
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _storage(path: str) -> list:
|
|
124
|
+
if path == ":memory:" or path.startswith("file:"):
|
|
125
|
+
return []
|
|
126
|
+
directory = os.path.dirname(os.path.abspath(path)) or "."
|
|
127
|
+
probe = directory
|
|
128
|
+
while not os.path.exists(probe):
|
|
129
|
+
parent = os.path.dirname(probe)
|
|
130
|
+
if parent == probe:
|
|
131
|
+
break
|
|
132
|
+
probe = parent
|
|
133
|
+
target = path if os.path.exists(path) else probe
|
|
134
|
+
if not os.access(target, os.W_OK):
|
|
135
|
+
return [
|
|
136
|
+
Error(
|
|
137
|
+
f"Redline cannot write its storage at {path!r}.",
|
|
138
|
+
hint="Point REDLINE['STORAGE_PATH'] at a writable location.",
|
|
139
|
+
id="django_redline.E002",
|
|
140
|
+
)
|
|
141
|
+
]
|
|
142
|
+
return []
|
django_redline/conf.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Settings: the ``REDLINE`` dict, mapped onto the core :class:`redline_core.Settings`.
|
|
2
|
+
|
|
3
|
+
Every key of ``settings.REDLINE`` is a core setting (case-insensitive, see
|
|
4
|
+
``redline_core.conf``) except the Django-only ones listed in :data:`DJANGO_KEYS`.
|
|
5
|
+
Defaults follow ``DEBUG``:
|
|
6
|
+
|
|
7
|
+
* ``SAMPLE_RATE`` is ``1.0`` (keep every request) with ``DEBUG = True`` and ``0.1`` with
|
|
8
|
+
``DEBUG = False``. Slow requests and 5xx errors are always kept either way.
|
|
9
|
+
* ``STORAGE_PATH`` is ``<BASE_DIR>/.redline/redline.db`` when ``BASE_DIR`` is set, and
|
|
10
|
+
``PROJECT_ROOT`` (used to tell your code from library code) is ``BASE_DIR``.
|
|
11
|
+
|
|
12
|
+
Django-only keys:
|
|
13
|
+
|
|
14
|
+
``PERMISSION``
|
|
15
|
+
Who may open the UI and the API: a callable ``(request) -> bool`` or its dotted path.
|
|
16
|
+
Default: active superusers (:func:`default_permission`; staff before 0.2).
|
|
17
|
+
``STORE``
|
|
18
|
+
Where traces go (the counterpart of FastAPI's ``install(store=...)``): a
|
|
19
|
+
:class:`~redline_core.storage.Store` instance, a callable (or class) taking the core
|
|
20
|
+
:class:`~redline_core.Settings` and returning one, or the dotted path of either.
|
|
21
|
+
Default: ``SQLiteStore.from_settings(settings)``.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import inspect
|
|
27
|
+
import os
|
|
28
|
+
from collections.abc import Callable
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from django.conf import settings
|
|
33
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
34
|
+
from django.http import HttpRequest
|
|
35
|
+
from django.utils.module_loading import import_string
|
|
36
|
+
|
|
37
|
+
from redline_core.conf import Settings, SettingsError
|
|
38
|
+
from redline_core.config import ResolvedConfig, resolve_settings
|
|
39
|
+
from redline_core.storage import SQLiteStore, Store
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"DJANGO_KEYS",
|
|
43
|
+
"PRODUCTION_SAMPLE_RATE",
|
|
44
|
+
"SETTING_NAME",
|
|
45
|
+
"DjangoOptions",
|
|
46
|
+
"build_store",
|
|
47
|
+
"default_permission",
|
|
48
|
+
"get_core_settings",
|
|
49
|
+
"get_options",
|
|
50
|
+
"get_resolved_config",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
SETTING_NAME = "REDLINE"
|
|
54
|
+
DJANGO_KEYS = ("permission", "store")
|
|
55
|
+
#: Default ``SAMPLE_RATE`` when ``DEBUG`` is False.
|
|
56
|
+
PRODUCTION_SAMPLE_RATE = 0.1
|
|
57
|
+
|
|
58
|
+
Permission = Callable[[HttpRequest], bool]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def default_permission(request: HttpRequest) -> bool:
|
|
62
|
+
"""Active superusers only (the default ``PERMISSION``; before 0.2 it was staff).
|
|
63
|
+
|
|
64
|
+
Staff status is often handed out for the admin of a single model; Redline shows every
|
|
65
|
+
captured request (headers, SQL, bodies) of every user, so the default asks for more.
|
|
66
|
+
Use ``REDLINE = {"PERMISSION": "django_redline.conf.staff_permission"}`` (or your own
|
|
67
|
+
callable) for the old behaviour."""
|
|
68
|
+
user = getattr(request, "user", None)
|
|
69
|
+
return bool(user is not None and user.is_active and user.is_superuser)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def staff_permission(request: HttpRequest) -> bool:
|
|
73
|
+
"""Active staff users (the default ``PERMISSION`` before 0.2)."""
|
|
74
|
+
user = getattr(request, "user", None)
|
|
75
|
+
return bool(user is not None and user.is_active and user.is_staff)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class DjangoOptions:
|
|
80
|
+
"""The Django-only part of ``REDLINE``."""
|
|
81
|
+
|
|
82
|
+
permission: Permission = default_permission
|
|
83
|
+
#: The ``STORE`` value after importing a dotted path (``None``: the SQLite default).
|
|
84
|
+
store: Any = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _raw() -> dict[str, Any]:
|
|
88
|
+
raw = getattr(settings, SETTING_NAME, None) or {}
|
|
89
|
+
if not isinstance(raw, dict):
|
|
90
|
+
raise ImproperlyConfigured(f"settings.{SETTING_NAME} must be a dict.")
|
|
91
|
+
for key in raw:
|
|
92
|
+
if not isinstance(key, str):
|
|
93
|
+
raise ImproperlyConfigured(f"settings.{SETTING_NAME} keys must be strings: {key!r}.")
|
|
94
|
+
return raw
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def get_resolved_config() -> ResolvedConfig:
|
|
98
|
+
"""The layered configuration (``redline_core.config``) with ``settings.REDLINE``
|
|
99
|
+
(minus Django-only keys) as the framework layer.
|
|
100
|
+
|
|
101
|
+
Adapter defaults (below a preset, the config file and ``REDLINE_*`` variables):
|
|
102
|
+
``sample_rate`` 0.1 without ``DEBUG``, ``storage_path``/``project_root`` from
|
|
103
|
+
``BASE_DIR``, and ``access="framework"`` (the ``PERMISSION`` check, default active
|
|
104
|
+
superusers) unless ``ACCESS`` is set explicitly.
|
|
105
|
+
|
|
106
|
+
Raises :class:`~django.core.exceptions.ImproperlyConfigured` for unknown keys or bad
|
|
107
|
+
values (the core's message, including its "did you mean" hint).
|
|
108
|
+
"""
|
|
109
|
+
raw = {k.lower(): v for k, v in _raw().items() if k.lower() not in DJANGO_KEYS}
|
|
110
|
+
defaults: dict[str, Any] = {}
|
|
111
|
+
base_dir = getattr(settings, "BASE_DIR", None)
|
|
112
|
+
if not settings.DEBUG:
|
|
113
|
+
defaults["sample_rate"] = PRODUCTION_SAMPLE_RATE
|
|
114
|
+
if base_dir is not None:
|
|
115
|
+
defaults["storage_path"] = os.path.join(str(base_dir), ".redline", "redline.db")
|
|
116
|
+
defaults["project_root"] = str(base_dir)
|
|
117
|
+
try:
|
|
118
|
+
return resolve_settings(raw, adapter_defaults=defaults, native_hook=True)
|
|
119
|
+
except SettingsError as exc:
|
|
120
|
+
raise ImproperlyConfigured(f"settings.{SETTING_NAME}: {exc}") from exc
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def get_core_settings() -> Settings:
|
|
124
|
+
"""``settings.REDLINE`` (minus Django-only keys) as core :class:`Settings` (see
|
|
125
|
+
:func:`get_resolved_config`)."""
|
|
126
|
+
return get_resolved_config().settings
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def get_options() -> DjangoOptions:
|
|
130
|
+
"""The Django-only options (``PERMISSION``, ``STORE``)."""
|
|
131
|
+
raw = {k.lower(): v for k, v in _raw().items()}
|
|
132
|
+
store = raw.get("store")
|
|
133
|
+
if isinstance(store, str):
|
|
134
|
+
try:
|
|
135
|
+
store = import_string(store)
|
|
136
|
+
except ImportError as exc:
|
|
137
|
+
raise ImproperlyConfigured(
|
|
138
|
+
f"settings.{SETTING_NAME}['STORE'] could not be imported: {exc}"
|
|
139
|
+
) from exc
|
|
140
|
+
if store is not None and not callable(store) and not isinstance(store, Store):
|
|
141
|
+
raise ImproperlyConfigured(
|
|
142
|
+
f"settings.{SETTING_NAME}['STORE'] must be a Store, a callable (settings) -> "
|
|
143
|
+
f"Store, or the dotted path of either; got {store!r}."
|
|
144
|
+
)
|
|
145
|
+
permission = raw.get("permission")
|
|
146
|
+
if permission is None:
|
|
147
|
+
return DjangoOptions(store=store)
|
|
148
|
+
if isinstance(permission, str):
|
|
149
|
+
try:
|
|
150
|
+
permission = import_string(permission)
|
|
151
|
+
except ImportError as exc:
|
|
152
|
+
raise ImproperlyConfigured(
|
|
153
|
+
f"settings.{SETTING_NAME}['PERMISSION'] could not be imported: {exc}"
|
|
154
|
+
) from exc
|
|
155
|
+
if not callable(permission):
|
|
156
|
+
raise ImproperlyConfigured(
|
|
157
|
+
f"settings.{SETTING_NAME}['PERMISSION'] must be a callable (request) -> bool "
|
|
158
|
+
"or its dotted path."
|
|
159
|
+
)
|
|
160
|
+
return DjangoOptions(permission=permission, store=store)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def build_store(spec: Any, core: Settings) -> tuple[Store, bool]:
|
|
164
|
+
"""``(store, owned)`` for a ``STORE`` value; ``owned`` stores are closed on rebuilds.
|
|
165
|
+
|
|
166
|
+
``None`` builds the default SQLite store. A class or plain callable is called with the
|
|
167
|
+
core settings. A ready instance is used as-is and is *not* closed when the runtime is
|
|
168
|
+
rebuilt (``override_settings``), only flushed – it outlives the runtime.
|
|
169
|
+
"""
|
|
170
|
+
if spec is None:
|
|
171
|
+
return SQLiteStore.from_settings(core), True
|
|
172
|
+
if inspect.isclass(spec) or (callable(spec) and not isinstance(spec, Store)):
|
|
173
|
+
store = spec(core)
|
|
174
|
+
owned = True
|
|
175
|
+
else:
|
|
176
|
+
store, owned = spec, False
|
|
177
|
+
if not isinstance(store, Store):
|
|
178
|
+
raise ImproperlyConfigured(
|
|
179
|
+
f"settings.{SETTING_NAME}['STORE'] produced {store!r}, which does not implement "
|
|
180
|
+
"the redline_core.storage.Store protocol."
|
|
181
|
+
)
|
|
182
|
+
return store, owned
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""The EXPLAIN executor the core API calls: Django ``connections[alias]``, always rolled back.
|
|
2
|
+
|
|
3
|
+
The statement runs through a normal Django cursor, so the captured ``%s`` placeholders work
|
|
4
|
+
on every backend (Django's cursor wrappers translate them to the driver's paramstyle). It
|
|
5
|
+
runs inside ``transaction.atomic`` with ``set_rollback(True)``, and on PostgreSQL – when it
|
|
6
|
+
owns the transaction – the transaction is also ``READ ONLY``. Nothing it executes is
|
|
7
|
+
recorded as a span.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable, Sequence
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from django.db import connections, transaction
|
|
16
|
+
from django.db.utils import ConnectionDoesNotExist
|
|
17
|
+
|
|
18
|
+
from .instrument import suppress
|
|
19
|
+
|
|
20
|
+
__all__ = ["executor_factory"]
|
|
21
|
+
|
|
22
|
+
Executor = Callable[[str, Any], Sequence[Sequence[Any]]]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def executor_factory(db_alias: str, vendor: str) -> Executor | None:
|
|
26
|
+
"""``(db_alias, vendor) -> executor`` for :class:`redline_core.api.RedlineAPI`."""
|
|
27
|
+
try:
|
|
28
|
+
connection = connections[db_alias]
|
|
29
|
+
except ConnectionDoesNotExist:
|
|
30
|
+
return None
|
|
31
|
+
if vendor not in ("postgresql", "mysql", "sqlite"):
|
|
32
|
+
return None
|
|
33
|
+
if connection.vendor != vendor:
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
def execute(sql: str, params: Any) -> list[Sequence[Any]]:
|
|
37
|
+
if isinstance(params, list):
|
|
38
|
+
params = tuple(params)
|
|
39
|
+
with suppress():
|
|
40
|
+
outermost = not connection.in_atomic_block
|
|
41
|
+
with transaction.atomic(using=db_alias):
|
|
42
|
+
try:
|
|
43
|
+
with connection.cursor() as cursor:
|
|
44
|
+
if outermost and connection.vendor == "postgresql":
|
|
45
|
+
cursor.execute("SET TRANSACTION READ ONLY")
|
|
46
|
+
cursor.execute(sql, params)
|
|
47
|
+
rows = list(cursor.fetchall())
|
|
48
|
+
finally:
|
|
49
|
+
transaction.set_rollback(True, using=db_alias)
|
|
50
|
+
return rows
|
|
51
|
+
|
|
52
|
+
return execute
|