sendproof-django 0.1.0a2__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,46 @@
1
+ """Sendproof workbench, rollback previews and observed sends for Django."""
2
+
3
+ from sendproof_core import AuthProvider, Identity
4
+ from sendproof_core.marker import apply_marker
5
+
6
+ from .orm import DjangoOrmPreview
7
+
8
+ __all__ = ["AuthProvider", "DjangoOrmPreview", "Identity", "close_sessions", "preview"]
9
+ __version__ = "0.1.0a2"
10
+
11
+
12
+ def close_sessions() -> None:
13
+ """Roll back held Preview sessions during worker shutdown."""
14
+ from .conf import get_bench
15
+
16
+ get_bench().engine.sessions.close()
17
+
18
+
19
+ def preview(view=True, *, methods=None, reason=None, stores=None):
20
+ """Mark a view, or a handler method of a class-based view, as eligible for previews.
21
+
22
+ A function view lists the methods it accepts for previews (default: the write methods
23
+ ``POST``, ``PUT``, ``PATCH``, ``DELETE``)::
24
+
25
+ @preview(methods=["POST"])
26
+ def create_item(request): ...
27
+
28
+ On a class-based view, DRF ``APIView``/``ViewSet`` or Django Ninja operation, decorate the
29
+ handler (``post``, ``create``, the Ninja function) directly, below the route decorator::
30
+
31
+ @api.post("/items")
32
+ @preview
33
+ def create_item(request, payload: ItemIn): ...
34
+
35
+ An operation you know writes to a store a Preview cannot roll back, such as one that clears a
36
+ Redis session, can be marked ``preview: false``. The workbench then shows "Preview
37
+ unavailable" with your reason before anyone tries, a Preview of it is refused (never
38
+ confirmed) without running the view, and Send still runs it::
39
+
40
+ @preview(False, methods=["DELETE"], reason="Clears the Redis session", stores=["redis"])
41
+ def delete_session(request, id): ...
42
+
43
+ Without ``reason`` the published reason names the first of ``stores``. The binding never
44
+ infers the mark: without it the operation is advertised and the write guard decides at run time.
45
+ """
46
+ return apply_marker(view, True, reason=reason, stores=stores, methods=methods)
@@ -0,0 +1,100 @@
1
+ """Builds the Sendproof engine from ``settings.SENDPROOF``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from typing import Any, Callable
7
+
8
+ from django.conf import settings
9
+ from django.utils.module_loading import import_string
10
+
11
+ from sendproof_core import AuthProvider, BenchOptions, Identity, OpenApiDocument
12
+ from sendproof_core.stores.base import DataStore, StoresOnlyProvider, validate_stores
13
+ from sendproof_core.sync_engine import SyncBench
14
+ from sendproof_core.workbench import Workbench
15
+
16
+ _lock = threading.Lock()
17
+ _bench: "DjangoBench | None" = None
18
+
19
+ KEYS = {
20
+ "API_NAME", "OPENAPI_URL", "DOCUMENTS", "ENVIRONMENT", "ENVIRONMENTS", "PROVIDER", "IDENTITY",
21
+ "AUTHORIZE", "AUTH_PROVIDERS", "FIELD_MODULES", "INCLUDE_SQL_PARAMETER_VALUES", "TRACE_TTL", "DATA_STORES",
22
+ "JOURNEY_FILES", "JOURNEYS", "JOURNEY_OPENAPI", "SESSION_IDLE_TIMEOUT", "SESSION_MAX_LIFETIME",
23
+ }
24
+
25
+
26
+ def default_identity(request: Any) -> Identity | None:
27
+ """Identity of ``request.user`` when Django authentication has established one."""
28
+ user = getattr(request, "user", None)
29
+ if user is None or not user.is_authenticated:
30
+ return None
31
+ name = user.get_full_name() or user.get_username()
32
+ return Identity(name, None, str(user.pk), "django")
33
+
34
+
35
+ def _resolve(value: Any) -> Any:
36
+ return import_string(value) if isinstance(value, str) else value
37
+
38
+
39
+ class DjangoBench:
40
+ """The configured engine plus the hooks supplied in settings."""
41
+
42
+ def __init__(self, config: dict[str, Any]) -> None:
43
+ unknown = set(config) - KEYS
44
+ if unknown:
45
+ raise ValueError(f"Unknown SENDPROOF setting(s): {', '.join(sorted(unknown))}")
46
+ provider = _resolve(config.get("PROVIDER"))
47
+ if callable(provider) and not hasattr(provider, "begin"):
48
+ provider = provider()
49
+ stores = []
50
+ for entry in config.get("DATA_STORES", ()):
51
+ store = _resolve(entry)
52
+ stores.append(store() if callable(store) and not isinstance(store, DataStore) else store)
53
+ stores = validate_stores(stores)
54
+ # Without a SQL provider, hooked stores alone can carry a Preview (see sendproof_fastapi).
55
+ if provider is None and stores:
56
+ provider = StoresOnlyProvider()
57
+ self.identity: Callable[[Any], Identity | None] = _resolve(config.get("IDENTITY")) or default_identity
58
+ authorize = _resolve(config.get("AUTHORIZE"))
59
+ providers = [
60
+ p if isinstance(p, AuthProvider) else AuthProvider(p["label"], p["kind"], p.get("url"))
61
+ for p in config.get("AUTH_PROVIDERS", [])
62
+ ]
63
+ documents = [
64
+ d if isinstance(d, OpenApiDocument) else OpenApiDocument(d["name"], d["url"])
65
+ for d in config.get("DOCUMENTS", [])
66
+ ]
67
+ self.options = BenchOptions(
68
+ api_name=config.get("API_NAME"), openapi_url=config.get("OPENAPI_URL"), documents=documents,
69
+ environment=config.get("ENVIRONMENT"), environments=tuple(config.get("ENVIRONMENTS", ("Development",))),
70
+ auth_providers=providers, field_modules=list(config.get("FIELD_MODULES", [])),
71
+ include_sql_parameter_values=config.get("INCLUDE_SQL_PARAMETER_VALUES"),
72
+ trace_ttl=float(config.get("TRACE_TTL", 300.0)), identity=self.identity, framework="Django",
73
+ journey_files=tuple(config.get("JOURNEY_FILES", ())),
74
+ session_idle_timeout=config.get("SESSION_IDLE_TIMEOUT", 300),
75
+ session_max_lifetime=config.get("SESSION_MAX_LIFETIME", 1800),
76
+ journeys=tuple(config.get("JOURNEYS", ())),
77
+ )
78
+ self.provider = provider
79
+ schema_factory = config.get("JOURNEY_OPENAPI")
80
+ openapi = (lambda: import_string(schema_factory)()) if isinstance(schema_factory, str) else schema_factory
81
+ self.workbench = Workbench(self.options, provider, journey_openapi=openapi)
82
+ self.engine = SyncBench(self.options, provider, self.workbench, authorize, stores)
83
+
84
+
85
+ def get_bench() -> DjangoBench:
86
+ """The process-wide engine, built on first use from ``settings.SENDPROOF``."""
87
+ global _bench
88
+ with _lock:
89
+ if _bench is None:
90
+ _bench = DjangoBench(dict(getattr(settings, "SENDPROOF", {})))
91
+ return _bench
92
+
93
+
94
+ def reset() -> None:
95
+ """Forget the cached engine (tests)."""
96
+ global _bench
97
+ with _lock:
98
+ if _bench is not None:
99
+ _bench.engine.sessions.close()
100
+ _bench = None
@@ -0,0 +1,117 @@
1
+ """Finds previewable operations in a Django URLconf.
2
+
3
+ Three kinds of views are understood:
4
+
5
+ * plain function views decorated with :func:`sendproof_django.preview`;
6
+ * class-based views and Django REST framework views or viewsets whose handler methods
7
+ (``post``, ``create``...) are decorated;
8
+ * Django Ninja operations, whose handler functions are decorated.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from typing import Any, Iterable, Iterator
15
+
16
+ from django.urls import URLPattern, URLResolver
17
+ from django.urls.resolvers import RoutePattern
18
+
19
+ from sendproof_core.marker import is_marked, is_previewable, marked_methods, unavailable_info
20
+
21
+ _CONVERTER = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>")
22
+ _HTTP_METHODS = ("get", "post", "put", "patch", "delete")
23
+
24
+
25
+ def _ninja_operations(callback: Any) -> Any:
26
+ """The operations of a Django Ninja path view, found on the bound view or in its closure."""
27
+ owners = [getattr(callback, "__self__", None)]
28
+ for cell in getattr(callback, "__closure__", None) or ():
29
+ try:
30
+ owners.append(cell.cell_contents)
31
+ except ValueError: # an empty cell
32
+ continue
33
+ for owner in owners:
34
+ operations = getattr(owner, "operations", None)
35
+ if isinstance(operations, (list, tuple)):
36
+ return operations
37
+ return None
38
+
39
+
40
+ def view_methods(callback: Any, *, unavailable: bool = False, observed: bool = False) -> set[str]:
41
+ """HTTP methods for which ``callback`` has a handler a Preview may run.
42
+
43
+ With ``unavailable`` true, the methods whose handler is marked ``preview: false`` instead;
44
+ with ``observed`` true, every marked handler, since an observed Send may trace both.
45
+ """
46
+ def wanted(handler: Any) -> bool:
47
+ if observed:
48
+ return is_marked(handler)
49
+ return (unavailable_info(handler) is not None) if unavailable else is_previewable(handler)
50
+
51
+ methods: set[str] = set()
52
+ operations = _ninja_operations(callback)
53
+ if operations is not None: # Django Ninja path view
54
+ for operation in operations:
55
+ if wanted(getattr(operation, "view_func", None)):
56
+ methods.update(m.upper() for m in operation.methods)
57
+ return methods
58
+ cls = getattr(callback, "view_class", None) or getattr(callback, "cls", None)
59
+ if cls is not None:
60
+ actions = getattr(callback, "actions", None) # DRF viewset: {"post": "create"}
61
+ for method in _HTTP_METHODS:
62
+ name = actions.get(method) if actions is not None else method
63
+ if name and wanted(getattr(cls, name, None)):
64
+ methods.add(method.upper())
65
+ return methods
66
+ if wanted(callback):
67
+ methods.update(marked_methods(callback))
68
+ return methods
69
+
70
+
71
+ def _walk(patterns: Iterable[Any], prefix: str) -> Iterator[tuple[str, Any]]:
72
+ for entry in patterns:
73
+ if not isinstance(entry.pattern, RoutePattern):
74
+ continue # regex routes have no portable OpenAPI template
75
+ route = prefix + str(entry.pattern)
76
+ if isinstance(entry, URLResolver):
77
+ yield from _walk(entry.url_patterns, route)
78
+ elif isinstance(entry, URLPattern):
79
+ yield route, entry.callback
80
+
81
+
82
+ def _reason(callback: Any) -> Any:
83
+ """The ``preview: false`` mark of the first handler of ``callback`` that has one."""
84
+ operations = _ninja_operations(callback)
85
+ if operations is not None:
86
+ handlers = [getattr(operation, "view_func", None) for operation in operations]
87
+ else:
88
+ cls = getattr(callback, "view_class", None) or getattr(callback, "cls", None)
89
+ actions = getattr(callback, "actions", None)
90
+ handlers = (
91
+ [getattr(cls, (actions.get(m) if actions is not None else m) or "", None) for m in _HTTP_METHODS]
92
+ if cls is not None else [callback]
93
+ )
94
+ return next((info for info in map(unavailable_info, handlers) if info is not None), None)
95
+
96
+
97
+ def unavailable_operations(patterns: Iterable[Any]) -> list[tuple[str, str, str, tuple[str, ...]]]:
98
+ """Method, path, reason and stores of every operation marked ``preview: false``."""
99
+ found = []
100
+ for route, callback in _walk(patterns, ""):
101
+ methods = view_methods(callback, unavailable=True)
102
+ marked = _reason(callback) if methods else None
103
+ if marked is not None:
104
+ path = "/" + _CONVERTER.sub(r"{\1}", route).lstrip("/")
105
+ found.extend((method, path, marked.reason, marked.stores) for method in sorted(methods))
106
+ return found
107
+
108
+
109
+ def preview_operations(patterns: Iterable[Any]) -> list[tuple[str, str]]:
110
+ """Method and OpenAPI path template of every operation a Preview may run."""
111
+ found = []
112
+ for route, callback in _walk(patterns, ""):
113
+ methods = view_methods(callback)
114
+ if methods:
115
+ path = "/" + _CONVERTER.sub(r"{\1}", route).lstrip("/")
116
+ found.extend((method, path) for method in sorted(methods))
117
+ return found
@@ -0,0 +1,282 @@
1
+ """Django middleware that serves the workbench and runs previews and observed sends.
2
+
3
+ Add it **last** in ``MIDDLEWARE`` so that sessions, authentication and your own middleware have
4
+ already run when it asks for an identity, and so that the real URL resolution, view middleware
5
+ and view of the target run for a preview.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import logging
12
+ import threading
13
+ import time
14
+ from typing import Any, Callable
15
+
16
+ from django.http import HttpRequest, HttpResponse
17
+ from django.urls import Resolver404, get_script_prefix, get_urlconf, get_resolver, resolve
18
+
19
+ from sendproof_core import limits, protocol
20
+ from sendproof_core.marker import enter
21
+ from sendproof_core.scope import install_logging_capture, request_context
22
+ from sendproof_core.sessions import HEADER, HeldSession, SessionError, session_id
23
+ from sendproof_core.sync_engine import Inner, ResponseTooLarge, is_application_response
24
+ from sendproof_core.workbench import Response, problem_response
25
+
26
+ from . import conf
27
+ from .discovery import preview_operations, unavailable_operations, view_methods
28
+
29
+ logger = logging.getLogger("sendproof_django")
30
+
31
+ #: Request attribute of a re-dispatched preview: the view callback checked before it runs.
32
+ #: Only this middleware sets it; HTTP clients cannot set attributes on the request object.
33
+ PREVIEW_VIEW = "_sendproof_preview_view"
34
+
35
+ _chain_lock = threading.Lock()
36
+ _chain: Callable[[HttpRequest], HttpResponse] | None = None
37
+
38
+
39
+ def _middleware_chain() -> Callable[[HttpRequest], HttpResponse]:
40
+ """A complete synchronous ``MIDDLEWARE`` chain for previews, built once per process.
41
+
42
+ It is the same chain Django's own handlers build (and that its test client uses), so every
43
+ middleware, including path-based ones, sees the preview target path.
44
+ """
45
+ global _chain
46
+ with _chain_lock:
47
+ if _chain is None:
48
+ from django.core.handlers.base import BaseHandler
49
+
50
+ handler = BaseHandler()
51
+ handler.load_middleware(is_async=False)
52
+ _chain = handler._middleware_chain
53
+ return _chain
54
+
55
+
56
+ def reset_chain() -> None:
57
+ """Forget the cached preview chain (tests that change ``MIDDLEWARE``)."""
58
+ global _chain
59
+ with _chain_lock:
60
+ _chain = None
61
+
62
+
63
+ def _to_http(response: Response, head: bool = False) -> HttpResponse:
64
+ result = HttpResponse(b"" if head else response.body, status=response.status)
65
+ for name, value in response.headers:
66
+ result[name] = value
67
+ return result
68
+
69
+
70
+ class SendproofMiddleware:
71
+ """Intercepts ``/sendproof/*`` and Preview/Observed requests; everything else passes through."""
72
+
73
+ __test__ = False
74
+
75
+ def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
76
+ self.get_response = get_response
77
+ bench = conf.get_bench()
78
+ if bench.options.enabled:
79
+ install_logging_capture()
80
+
81
+ def __call__(self, request: HttpRequest) -> HttpResponse:
82
+ # Every request is attributed, so a store write that no request accounts for (a thread a
83
+ # Preview handler started without its context) can fail the open Previews. The body of a
84
+ # streaming response is produced after this returns and is not covered.
85
+ with request_context():
86
+ return self._handle(request)
87
+
88
+ def _handle(self, request: HttpRequest) -> HttpResponse:
89
+ bench = conf.get_bench()
90
+ if not bench.options.enabled:
91
+ return self.get_response(request)
92
+ expected = getattr(request, PREVIEW_VIEW, None)
93
+ if expected is not None:
94
+ return self._inner_preview(request, expected)
95
+ started = time.perf_counter()
96
+ path, engine = request.path_info, bench.engine
97
+ if engine.is_reserved(path):
98
+ if engine.is_preview_path(path):
99
+ return _to_http(self._preview(request, bench, path, started))
100
+ return _to_http(self._workbench(request, bench, path), request.method == "HEAD")
101
+ headers = _Headers(request)
102
+ if protocol.requests_rollback(headers.getlist):
103
+ return _to_http(problem_response(400, "Use the Sendproof preview URL for rollback requests."))
104
+ if request.method != "HEAD" and protocol.requests_trace(headers.getlist):
105
+ observed = self._observed(request, bench, headers, started)
106
+ if observed is not None:
107
+ return self._run_observed(request, observed)
108
+ return self.get_response(request)
109
+
110
+ # ------------------------------------------------------------------ helpers
111
+ @staticmethod
112
+ def _origin_ok(request: HttpRequest, headers: "_Headers") -> bool:
113
+ return protocol.is_same_origin(headers.getlist, request.scheme, request.get_host())
114
+
115
+ @staticmethod
116
+ def _identity(request: HttpRequest, bench: Any) -> Any:
117
+ try:
118
+ return bench.identity(request)
119
+ except Exception:
120
+ logger.exception("The Sendproof identity resolver failed; treating the caller as anonymous.")
121
+ return None
122
+
123
+ @staticmethod
124
+ def _authorized(request: HttpRequest, bench: Any, identity: Any) -> bool:
125
+ hook = bench.engine.authorize
126
+ if hook is None:
127
+ return True
128
+ try:
129
+ return bool(hook(request, identity))
130
+ except Exception:
131
+ logger.exception("The Sendproof authorization hook failed; denying access.")
132
+ return False
133
+
134
+ @staticmethod
135
+ def _path_base() -> str:
136
+ return get_script_prefix().rstrip("/")
137
+
138
+ def _match(self, request: HttpRequest, path: str) -> tuple[Any, int | None]:
139
+ """Resolve ``path`` with Django's own router: (match or None, failing status)."""
140
+ try:
141
+ return resolve(path, getattr(request, "urlconf", None) or get_urlconf()), None
142
+ except Resolver404:
143
+ return None, 404
144
+
145
+ def _inner_preview(self, request: HttpRequest, expected: Any) -> HttpResponse:
146
+ """Last check of a re-dispatched preview, after every other middleware has run.
147
+
148
+ Middleware may have changed the method or the path. Unless the request still resolves to
149
+ the marked view and method checked earlier, nothing runs and the preview answers 409.
150
+ """
151
+ match, _ = self._match(request, request.path_info)
152
+ expected_view, read_step = expected
153
+ if match is None or match.func is not expected_view:
154
+ return _to_http(problem_response(409, "This operation is unavailable for preview."))
155
+ if read_step and request.method == "GET" and "GET" not in view_methods(match.func, unavailable=True):
156
+ enter()
157
+ elif read_step or (request.method or "") not in view_methods(match.func):
158
+ return _to_http(problem_response(409, "This operation is unavailable for preview."))
159
+ return self.get_response(request)
160
+
161
+ # ---------------------------------------------------------------- workbench
162
+ def _workbench(self, request: HttpRequest, bench: Any, path: str) -> Response:
163
+ headers = _Headers(request)
164
+ identity = self._identity(request, bench)
165
+ conf_module = getattr(request, "urlconf", None) or get_urlconf()
166
+ return bench.engine.serve_workbench(
167
+ method=request.method or "GET", path=path, path_base=self._path_base(),
168
+ query=request.META.get("QUERY_STRING", ""), identity=identity,
169
+ authorized=self._authorized(request, bench, identity), origin_ok=self._origin_ok(request, headers),
170
+ operations=lambda: preview_operations(get_resolver(conf_module).url_patterns),
171
+ unavailable=lambda: unavailable_operations(get_resolver(conf_module).url_patterns),
172
+ default_openapi_url="/openapi.json", default_api_name="API",
173
+ read_body=lambda: request.read(4097),
174
+ )
175
+
176
+ # ------------------------------------------------------------------ preview
177
+ def _preview(self, request: HttpRequest, bench: Any, path: str, started: float) -> Response:
178
+ engine, headers, method = bench.engine, _Headers(request), request.method or "GET"
179
+ origin_ok = self._origin_ok(request, headers)
180
+ rejection = engine.check_preview_request(
181
+ method=method, path=path, get_header=headers.getlist, origin_ok=origin_ok,
182
+ )
183
+ if rejection is not None:
184
+ return rejection
185
+ identity = self._identity(request, bench)
186
+ try:
187
+ with engine.use_session(session_id(headers.getlist(HEADER)), identity, self._path_base(), origin_ok) as held:
188
+ return self._dispatch_preview(request, bench, path, started, identity, held)
189
+ except SessionError as error:
190
+ return error.response
191
+
192
+ def _dispatch_preview(self, request: HttpRequest, bench: Any, path: str, started: float,
193
+ identity: Any, held: HeldSession | None) -> Response:
194
+ engine, method = bench.engine, request.method or "GET"
195
+ target = path[len(protocol.PREVIEW_PREFIX):]
196
+ match, _ = self._match(request, target)
197
+ if match is None:
198
+ return problem_response(404, "The preview target was not found for this method.")
199
+ read_step = held is not None and method == "GET"
200
+ if method in view_methods(match.func, unavailable=True) or (not read_step and method not in view_methods(match.func)):
201
+ return problem_response(409, "This operation is unavailable for preview.")
202
+ if not self._authorized(request, bench, identity):
203
+ return problem_response(403 if identity else 401, "This preview is forbidden.")
204
+
205
+ def dispatch(scope: Any) -> Inner:
206
+ # A copy of the request runs the full middleware chain, so the outer request keeps its
207
+ # own session, user and META: session changes made during the preview are never saved
208
+ # by the outer SessionMiddleware nor sent as a cookie on the real response.
209
+ inner = copy.copy(request)
210
+ inner.META = dict(request.META)
211
+ if hasattr(inner, "environ"):
212
+ inner.environ = inner.META
213
+ inner.path_info = target
214
+ inner.path = self._path_base() + target
215
+ inner.META["PATH_INFO"] = target
216
+ inner.META.pop("HTTP_ACCEPT_ENCODING", None)
217
+ inner.META["HTTP_CACHE_CONTROL"] = "no-cache, no-store"
218
+ inner.resolver_match = None
219
+ setattr(inner, PREVIEW_VIEW, (match.func, read_step))
220
+ # response.close() is deliberately not called: it sends request_finished, whose
221
+ # close_old_connections receiver would close the connection mid-transaction.
222
+ response = _middleware_chain()(inner)
223
+ body = _bounded_body(response)
224
+ unhandled = scope.extensions.get("unhandled")
225
+ if unhandled is not None:
226
+ raise unhandled if isinstance(unhandled, BaseException) else RuntimeError("Unhandled application error.")
227
+ return Inner(response.status_code, [(k, v) for k, v in response.items()], body)
228
+
229
+ return engine.preview(dispatch=dispatch, started=started, method=method, path=path, held=held)
230
+
231
+ # ----------------------------------------------------------------- observed
232
+ def _observed(self, request: HttpRequest, bench: Any, headers: "_Headers", started: float) -> Any:
233
+ if not bench.engine.provider_available or not self._origin_ok(request, headers):
234
+ return None
235
+ match, _ = self._match(request, request.path_info)
236
+ if match is None or (request.method or "") not in view_methods(match.func, observed=True):
237
+ return None
238
+ identity = self._identity(request, bench)
239
+ return bench.engine.begin_observed(
240
+ identity=identity, path_base=self._path_base(), started=started,
241
+ authorized=self._authorized(request, bench, identity),
242
+ )
243
+
244
+ def _run_observed(self, request: HttpRequest, observed: Any) -> HttpResponse:
245
+ try:
246
+ response = self.get_response(request)
247
+ except BaseException:
248
+ observed.finish(False)
249
+ raise
250
+ if is_application_response(observed.scope, response.status_code):
251
+ for name, value in observed.headers():
252
+ response[name] = value
253
+ if response.streaming:
254
+ response._resource_closers.append(lambda: observed.finish(True))
255
+ else:
256
+ observed.finish(True)
257
+ return response
258
+
259
+
260
+ class _Headers:
261
+ """Adapts Django's merged header view to the protocol helpers."""
262
+
263
+ def __init__(self, request: HttpRequest) -> None:
264
+ self._headers = request.headers
265
+
266
+ def getlist(self, name: str) -> list[str]:
267
+ value = self._headers.get(name)
268
+ return [] if value is None else [value]
269
+
270
+
271
+ def _bounded_body(response: HttpResponse) -> bytes:
272
+ if getattr(response, "streaming", False):
273
+ chunks, size = [], 0
274
+ for chunk in response.streaming_content:
275
+ size += len(chunk)
276
+ if size > limits.RESPONSE_BYTES:
277
+ raise ResponseTooLarge
278
+ chunks.append(chunk)
279
+ return b"".join(chunks)
280
+ if len(response.content) > limits.RESPONSE_BYTES:
281
+ raise ResponseTooLarge
282
+ return response.content
@@ -0,0 +1,582 @@
1
+ """Django ORM implementation of the Sendproof preview provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import sys
7
+ import threading
8
+ import time
9
+ from contextlib import contextmanager
10
+ from pathlib import Path
11
+ from typing import Any, Iterable
12
+
13
+ from django.core.signals import got_request_exception
14
+ from django.db import connections, transaction
15
+ from django.db.models.signals import post_delete, post_save, pre_delete, pre_save
16
+
17
+ from sendproof_core import (
18
+ PreviewChange,
19
+ PreviewObservation,
20
+ PreviewProvider,
21
+ PreviewRollbackError,
22
+ PreviewSession,
23
+ PreviewUnavailable,
24
+ RequestScope,
25
+ limits,
26
+ )
27
+ from sendproof_core.jsonsafe import is_missing, snapshot
28
+ from sendproof_core.redaction import describe_parameters, python_type_name
29
+ from sendproof_core.scope import current_scope
30
+ from sendproof_core.sessions import HeldPart, StepFailed, StoreBusy, StoreEnded, savepoint
31
+ from sendproof_core.txguard import escapes_transaction, normalize_procedures, server_ended_transaction
32
+
33
+ STATE_KEY = "django_orm"
34
+ _UID = "sendproof_django"
35
+ _connected = False
36
+
37
+ #: The savepoint every Preview opens its transaction with. Django names its own savepoints
38
+ #: ``s<thread>_x<n>``, so it never makes this one, and a handler's ``RELEASE`` or ``ROLLBACK TO`` of it
39
+ #: is refused like a ``COMMIT``.
40
+ SAVEPOINT = "sendproof_preview"
41
+
42
+ #: Django's own savepoint statements, which may still run after the server ended the Preview transaction.
43
+ _SAVEPOINT_CONTROL = re.compile(r"\s*(?:ROLLBACK\s+TO\s+SAVEPOINT|RELEASE\s+SAVEPOINT)\s+[`\"]?s\d+_x\d+[`\"]?\s*$", re.I)
44
+
45
+
46
+ def _raw(alias: str, statement: str) -> None:
47
+ """Run ``statement`` on the alias's DBAPI connection, past the execute wrappers and the SQL log."""
48
+ cursor = connections[alias].connection.cursor()
49
+ try:
50
+ cursor.execute(statement)
51
+ finally:
52
+ cursor.close()
53
+
54
+ #: One lock per MySQL database alias; a preview holds it from its first transaction until rollback.
55
+ _mysql_turns: dict[str, threading.Lock] = {}
56
+ _mysql_turns_guard = threading.Lock()
57
+
58
+
59
+ def _take_mysql_turn(alias: str, *, nowait: bool = False) -> threading.Lock:
60
+ """Wait until no other preview on ``alias`` runs, and answer the held lock.
61
+
62
+ InnoDB checks a new key for duplicates under a shared lock. When three or more transactions insert the
63
+ same key and the first one rolls back, as every preview does, the waiters each hold that shared lock and
64
+ each need the exclusive one, so InnoDB aborts all but one with a deadlock (error 1213). Sent for real,
65
+ the first insert commits and the others get a duplicate-key error instead. MySQL previews therefore take
66
+ turns, as SQLite previews queue behind ``BEGIN IMMEDIATE``.
67
+ """
68
+ with _mysql_turns_guard:
69
+ lock = _mysql_turns.setdefault(alias, threading.Lock())
70
+ if not lock.acquire(blocking=not nowait):
71
+ raise StoreBusy(alias)
72
+ return lock
73
+
74
+
75
+ def _enter_atomic(alias: str) -> Any:
76
+ """Open the preview's ``atomic`` block on ``alias`` and answer it.
77
+
78
+ On SQLite the outermost block opens with ``BEGIN IMMEDIATE`` unless the database already sets an
79
+ IMMEDIATE or EXCLUSIVE ``transaction_mode``. A deferred ``BEGIN`` takes only a read lock, so two
80
+ previews that read and then write one row both hold it, and the second to write fails at once with
81
+ "database is locked" instead of waiting. Taking the write lock up front makes previews queue instead.
82
+ """
83
+ connection = connections[alias]
84
+ atomic = transaction.atomic(using=alias)
85
+ immediate = (
86
+ connection.vendor == "sqlite"
87
+ and connection.get_autocommit()
88
+ and (getattr(connection, "transaction_mode", None) or "DEFERRED") == "DEFERRED"
89
+ )
90
+ if not immediate:
91
+ atomic.__enter__()
92
+ return atomic
93
+ # Django starts an SQLite transaction through this hook; Django 4.2 to 5.0 always issue a plain BEGIN.
94
+ connection._start_transaction_under_autocommit = lambda: connection.cursor().execute("BEGIN IMMEDIATE")
95
+ try:
96
+ atomic.__enter__()
97
+ finally:
98
+ del connection._start_transaction_under_autocommit # back to the class's method
99
+ return atomic
100
+
101
+
102
+ def _json_value(value: Any) -> Any:
103
+ shown = snapshot(value)
104
+ return str(value) if is_missing(shown) else shown
105
+
106
+
107
+ class _State:
108
+ """Per-request state: the open transactions, SQL wrappers and captured changes."""
109
+
110
+ def __init__(self, aliases: tuple[str, ...], rollback: bool,
111
+ safe_procedures: frozenset[str] = frozenset()) -> None:
112
+ self.aliases = aliases
113
+ self.rollback = rollback
114
+ #: Procedures the host declared never commit; any other MySQL ``CALL`` is refused.
115
+ self.safe_procedures = safe_procedures
116
+ #: MySQL aliases whose Preview transaction opened with the ``SAVEPOINT`` the backstop checks.
117
+ self.marked: list[str] = []
118
+ #: Aliases whose Preview transaction the server itself ended (a deadlock), with the reason.
119
+ self.ended: dict[str, str] = {}
120
+ self.changes: list[PreviewChange] = []
121
+ self.changes_truncated = False
122
+ self.silent = 0 # >0 while Sendproof runs its own reads
123
+ self.pending: dict[int, dict[str, Any] | None] = {}
124
+ self.atomics: list[tuple[str, Any]] = []
125
+ #: The MySQL turns this preview holds (see ``_take_mysql_turn``), released when it ends.
126
+ self.turns: list[threading.Lock] = []
127
+ self.wrappers: list[tuple[Any, Any]] = []
128
+ self.finished = False
129
+ #: Why the rollback cannot be trusted, set when SQL tried to end the preview transaction.
130
+ self.unsafe: str | None = None
131
+
132
+ def add_change(self, change: PreviewChange) -> None:
133
+ if len(self.changes) >= limits.CHANGES:
134
+ self.changes_truncated = True
135
+ else:
136
+ self.changes.append(change)
137
+
138
+ # -- SQL capture
139
+ def install_wrappers(self) -> None:
140
+ for alias in self.aliases:
141
+ connection = connections[alias]
142
+ wrapper = self._wrapper
143
+ connection.execute_wrappers.append(wrapper)
144
+ self.wrappers.append((connection, wrapper))
145
+
146
+ def remove_wrappers(self) -> None:
147
+ for connection, wrapper in self.wrappers:
148
+ if wrapper in connection.execute_wrappers:
149
+ connection.execute_wrappers.remove(wrapper)
150
+ self.wrappers.clear()
151
+
152
+ def _wrapper(self, execute: Any, sql: str, params: Any, many: bool, context: dict) -> Any:
153
+ if self.rollback and not self.finished:
154
+ connection = context.get("connection")
155
+ alias = getattr(connection, "alias", "")
156
+ text = sql if isinstance(sql, str) else str(sql)
157
+ ended = self.ended.get(alias)
158
+ # Once the server ended the Preview transaction, a statement would run outside it. Django's own
159
+ # savepoint rollbacks still pass: they write nothing, and the handler keeps its original error.
160
+ if ended is not None and not _SAVEPOINT_CONTROL.match(text):
161
+ raise PreviewRollbackError(ended)
162
+ # A raw COMMIT (or DDL that MySQL and Oracle commit implicitly) would make the
163
+ # preview's writes durable before the rollback, so it never reaches the database.
164
+ vendor = getattr(connection, "vendor", "")
165
+ reason = escapes_transaction(text, vendor, SAVEPOINT, self.safe_procedures)
166
+ if reason is not None:
167
+ self.unsafe = reason
168
+ raise PreviewRollbackError(reason)
169
+ try:
170
+ return self._capture(execute, sql, params, many, context)
171
+ except Exception as error:
172
+ self._notice_server_rollback(error, alias, vendor)
173
+ raise
174
+ return self._capture(execute, sql, params, many, context)
175
+
176
+ def _notice_server_rollback(self, error: BaseException, alias: str, vendor: str) -> None:
177
+ """Remember a MySQL deadlock (or rolled-back lock wait timeout) that ended the Preview transaction."""
178
+ if alias in self.ended:
179
+ return
180
+
181
+ def rollback_on_timeout() -> bool:
182
+ try:
183
+ cursor = connections[alias].connection.cursor()
184
+ try:
185
+ cursor.execute("SELECT @@innodb_rollback_on_timeout")
186
+ return bool(int(cursor.fetchone()[0]))
187
+ finally:
188
+ cursor.close()
189
+ except Exception: # noqa: BLE001 - unknown: assume the transaction is gone
190
+ return True
191
+
192
+ reason = server_ended_transaction(error, vendor, rollback_on_timeout)
193
+ if reason is not None:
194
+ self.ended[alias] = reason
195
+ self.unsafe = self.unsafe or reason
196
+
197
+ def _capture(self, execute: Any, sql: str, params: Any, many: bool, context: dict) -> Any:
198
+ scope = current_scope()
199
+ if scope is None or self.silent or not scope.capture.is_active:
200
+ return execute(sql, params, many, context)
201
+ started = time.perf_counter()
202
+ try:
203
+ return execute(sql, params, many, context)
204
+ finally:
205
+ duration = (time.perf_counter() - started) * 1000
206
+ try:
207
+ named = _named_parameters(params, many)
208
+ listed, truncated = describe_parameters(sql, named, scope.include_sql_parameter_values)
209
+ rows = getattr(context.get("cursor"), "rowcount", None)
210
+ scope.capture.record_sql(
211
+ sql, listed, rows_affected=rows if isinstance(rows, int) and rows >= 0 else None,
212
+ duration_ms=duration, category="django.db.backends", truncated=truncated or many,
213
+ )
214
+ except Exception: # capture must never interrupt the application
215
+ pass
216
+
217
+
218
+ def _named_parameters(params: Any, many: bool) -> list[tuple[str, Any, str]]:
219
+ if many and params:
220
+ params = next(iter(params), None)
221
+ if isinstance(params, dict):
222
+ return [(str(k), v, python_type_name(v)) for k, v in params.items()]
223
+ if isinstance(params, (list, tuple)):
224
+ return [(f"p{i}", v, python_type_name(v)) for i, v in enumerate(params)]
225
+ return []
226
+
227
+
228
+ def _row(instance: Any) -> dict[str, Any]:
229
+ return {field.column: _json_value(field.value_from_object(instance)) for field in instance._meta.concrete_fields}
230
+
231
+
232
+ def _stored_row(model: Any, using: str, pk: Any, state: _State) -> dict[str, Any] | None:
233
+ """Read the row as stored. The read is not logged."""
234
+ if pk is None:
235
+ return None
236
+ state.silent += 1
237
+ try:
238
+ columns = {f.attname: f.column for f in model._meta.concrete_fields}
239
+ values = model._base_manager.using(using).filter(pk=pk).values(*columns).first()
240
+ finally:
241
+ state.silent -= 1
242
+ return None if values is None else {columns[name]: _json_value(value) for name, value in values.items()}
243
+
244
+
245
+ def _state_for(using: str) -> _State | None:
246
+ scope = current_scope()
247
+ state = scope.extensions.get(STATE_KEY) if scope else None
248
+ return state if state is not None and not state.finished and using in state.aliases else None
249
+
250
+
251
+ def _key(instance: Any) -> dict[str, Any]:
252
+ pk = instance._meta.pk
253
+ return {pk.column: _json_value(pk.value_from_object(instance))}
254
+
255
+
256
+ def _on_pre_save(sender: Any, instance: Any, raw: bool = False, using: str = "default", **kwargs: Any) -> None:
257
+ if (state := _state_for(using)) is not None and not raw:
258
+ state.pending[id(instance)] = _stored_row(sender, using, instance.pk, state)
259
+
260
+
261
+ def _on_post_save(sender: Any, instance: Any, created: bool, raw: bool = False, using: str = "default", **kwargs: Any) -> None:
262
+ if (state := _state_for(using)) is None or raw:
263
+ return
264
+ before = state.pending.pop(id(instance), None)
265
+ state.add_change(PreviewChange(
266
+ "insert" if created else "update", sender._meta.db_table, _key(instance),
267
+ None if created else before, _row(instance),
268
+ ))
269
+
270
+
271
+ def _on_pre_delete(sender: Any, instance: Any, using: str = "default", **kwargs: Any) -> None:
272
+ if (state := _state_for(using)) is not None:
273
+ state.pending[id(instance)] = _stored_row(sender, using, instance.pk, state) or _row(instance)
274
+
275
+
276
+ def _on_post_delete(sender: Any, instance: Any, using: str = "default", **kwargs: Any) -> None:
277
+ if (state := _state_for(using)) is not None:
278
+ before = state.pending.pop(id(instance), None) or _row(instance)
279
+ state.add_change(PreviewChange("delete", sender._meta.db_table, _key(instance), before, None))
280
+
281
+
282
+ def _on_unhandled(sender: Any, request: Any = None, **kwargs: Any) -> None:
283
+ """Django turns unhandled errors into 500 responses; remember them so a preview can fail."""
284
+ scope = current_scope()
285
+ if scope is not None:
286
+ scope.extensions["unhandled"] = sys.exc_info()[1] or True
287
+
288
+
289
+ def install_signals() -> None:
290
+ """Connect the change-capture receivers once per process."""
291
+ global _connected
292
+ if not _connected:
293
+ for signal, receiver in ((pre_save, _on_pre_save), (post_save, _on_post_save),
294
+ (pre_delete, _on_pre_delete), (post_delete, _on_post_delete)):
295
+ signal.connect(receiver, weak=False, dispatch_uid=f"{_UID}.{receiver.__name__}")
296
+ got_request_exception.connect(_on_unhandled, weak=False, dispatch_uid=f"{_UID}.unhandled")
297
+ _connected = True
298
+
299
+
300
+ class DjangoOrmPreview(PreviewProvider):
301
+ """Rolls back and observes the writes of an application that uses the Django ORM.
302
+
303
+ ``using`` lists the database aliases to enroll (default: ``("default",)``). ``database`` is a
304
+ public label for the workbench; never put a connection string in it.
305
+
306
+ On MySQL and MariaDB a Preview refuses ``CALL``, because a stored procedure can commit the
307
+ Preview transaction. ``safe_procedures`` lists procedures the host declares never commit, by
308
+ exact name (optionally ``schema.name``; case-insensitive, like MySQL): a ``CALL`` of one of
309
+ them is allowed. The binding trusts the declaration; a listed procedure that does commit is
310
+ caught by the savepoint check before the rollback, which answers 500, but its writes stay.
311
+ """
312
+
313
+ def __init__(self, using: Iterable[str] = ("default",), database: str | None = None,
314
+ safe_procedures: Iterable[str] = ()) -> None:
315
+ self.aliases = tuple(using)
316
+ if not self.aliases:
317
+ raise ValueError("Pass at least one database alias.")
318
+ self.database = database
319
+ self.safe_procedures = normalize_procedures(safe_procedures)
320
+ install_signals()
321
+
322
+ @property
323
+ def system(self) -> str | None: # type: ignore[override]
324
+ """The SQL provider id the workbench shows a store mark for: Django's ``vendor`` of the first database."""
325
+ try:
326
+ return str(connections[self.aliases[0]].vendor)
327
+ except Exception:
328
+ return None
329
+
330
+ def begin(self, scope: RequestScope) -> PreviewSession:
331
+ state = self._begin()
332
+ scope.extensions[STATE_KEY] = state
333
+ return _Session(state)
334
+
335
+ def _begin(self, *, held: bool = False) -> _State:
336
+ state = _State(self.aliases, rollback=True, safe_procedures=self.safe_procedures)
337
+ try:
338
+ for alias in self.aliases:
339
+ connection = connections[alias]
340
+ if not connection.features.supports_transactions:
341
+ raise PreviewUnavailable(f"Database '{alias}' does not support transactions.")
342
+ if connection.vendor == "mysql":
343
+ state.turns.append(_take_mysql_turn(alias, nowait=held))
344
+ state.atomics.append((alias, _open_atomic(alias, held)))
345
+ # The backstop's mark, made first thing in the Preview transaction (see ``rollback``).
346
+ _raw(alias, "SAVEPOINT " + SAVEPOINT)
347
+ state.marked.append(alias)
348
+ state.install_wrappers()
349
+ except BaseException:
350
+ _Session(state).close()
351
+ raise
352
+ return state
353
+
354
+ def supports_held(self, asynchronous: bool) -> bool:
355
+ for alias in self.aliases:
356
+ connection = connections[alias]
357
+ if connection.vendor not in ("sqlite", "postgresql", "mysql") or (
358
+ connection.vendor == "sqlite" and connection.is_in_memory_db()
359
+ ):
360
+ return False
361
+ return not asynchronous
362
+
363
+ def hold(self) -> HeldPart:
364
+ return _Held(self)
365
+
366
+ def begin_observation(self, scope: RequestScope) -> PreviewObservation | None:
367
+ state = _State(self.aliases, rollback=False)
368
+ scope.extensions[STATE_KEY] = state
369
+ state.install_wrappers()
370
+ return _Observation(state)
371
+
372
+
373
+ class _Observation(PreviewObservation):
374
+ def __init__(self, state: _State) -> None:
375
+ self._state = state
376
+
377
+ @property
378
+ def changes(self) -> list[PreviewChange]:
379
+ return self._state.changes
380
+
381
+ @property
382
+ def changes_truncated(self) -> bool:
383
+ return self._state.changes_truncated
384
+
385
+ def close(self) -> None:
386
+ self._state.finished = True
387
+ self._state.remove_wrappers()
388
+
389
+
390
+ class _Session(PreviewSession):
391
+ """Ends every enrolled ``atomic`` block with a rollback and confirms it."""
392
+
393
+ def __init__(self, state: _State) -> None:
394
+ self._state = state
395
+ self._rolled_back = False
396
+
397
+ @property
398
+ def changes(self) -> list[PreviewChange]:
399
+ return self._state.changes
400
+
401
+ @property
402
+ def changes_truncated(self) -> bool:
403
+ return self._state.changes_truncated
404
+
405
+ def rollback(self) -> None:
406
+ state = self._state
407
+ errors: list[BaseException] = []
408
+ for alias in state.marked:
409
+ # The backstop, on every database: the savepoint made when the Preview transaction opened
410
+ # must still exist. Any commit, explicit or implicit, erases every savepoint, and the driver
411
+ # (or MySQL with autocommit off) then opens a new transaction by itself, so a savepoint made now would
412
+ # prove nothing. Error 1305 (or a lost connection) means the rollback can't be confirmed.
413
+ try:
414
+ _raw(alias, "ROLLBACK TO SAVEPOINT " + SAVEPOINT)
415
+ except Exception: # noqa: BLE001 - reported through ``unsafe``
416
+ state.unsafe = state.unsafe or (
417
+ "The Preview transaction was committed before its rollback (its savepoint is gone), "
418
+ "so the Preview can't be confirmed."
419
+ )
420
+ while state.atomics:
421
+ alias, atomic = state.atomics.pop()
422
+ try:
423
+ transaction.set_rollback(True, using=alias)
424
+ atomic.__exit__(None, None, None)
425
+ except BaseException as error: # noqa: BLE001 - reported below
426
+ errors.append(error)
427
+ if errors:
428
+ raise PreviewRollbackError("The database rollback could not be confirmed.") from errors[0]
429
+ if state.unsafe:
430
+ raise PreviewRollbackError(state.unsafe)
431
+ self._rolled_back = True
432
+
433
+ def close(self) -> None:
434
+ state = self._state
435
+ state.finished = True
436
+ state.remove_wrappers()
437
+ failure: BaseException | None = None
438
+ try:
439
+ while state.atomics: # only when rollback() did not run or failed part way
440
+ alias, atomic = state.atomics.pop()
441
+ try:
442
+ atomic.__exit__(RuntimeError, RuntimeError("preview abandoned"), None)
443
+ except RuntimeError:
444
+ pass
445
+ except BaseException as error: # noqa: BLE001
446
+ failure = failure or error
447
+ finally:
448
+ # The preview's transactions have ended, so the next MySQL preview may run.
449
+ while state.turns:
450
+ state.turns.pop().release()
451
+ if failure is not None:
452
+ raise failure
453
+
454
+
455
+ def _open_atomic(alias: str, held: bool) -> Any:
456
+ connection = connections[alias]
457
+ if not held or connection.vendor != "sqlite":
458
+ return _enter_atomic(alias)
459
+
460
+ connection.ensure_connection()
461
+ cursor = connection.connection.cursor()
462
+ try:
463
+ cursor.execute("PRAGMA busy_timeout")
464
+ timeout = int(cursor.fetchone()[0])
465
+ cursor.execute("PRAGMA busy_timeout=0")
466
+ try:
467
+ return _enter_atomic(alias)
468
+ except Exception as error:
469
+ if getattr(error.__cause__, "sqlite_errorcode", 0) & 0xff in (5, 6):
470
+ raise StoreBusy(Path(connection.settings_dict["NAME"]).name) from error
471
+ raise
472
+ finally:
473
+ cursor.execute(f"PRAGMA busy_timeout={timeout}")
474
+ finally:
475
+ cursor.close()
476
+
477
+
478
+ class _Held(HeldPart):
479
+ """Django wrappers belong to a request by default. Install private ones only during a step."""
480
+
481
+ def __init__(self, provider: DjangoOrmPreview) -> None:
482
+ self.provider = provider
483
+ self.wrappers = {alias: connections.create_connection(alias) for alias in provider.aliases}
484
+ for connection in self.wrappers.values():
485
+ connection.inc_thread_sharing()
486
+ self.binding = None
487
+ self.state = None
488
+ try:
489
+ with self._bound():
490
+ self.root = provider._begin(held=True)
491
+ self.root.remove_wrappers()
492
+ except BaseException:
493
+ self._close_connections()
494
+ raise
495
+
496
+ @contextmanager
497
+ def _bound(self):
498
+ previous = {alias: connections[alias] for alias in self.wrappers}
499
+ try:
500
+ for alias, connection in self.wrappers.items():
501
+ connections[alias] = connection
502
+ yield
503
+ finally:
504
+ for alias, connection in previous.items():
505
+ connections[alias] = connection
506
+
507
+ def _check(self) -> None:
508
+ if self.state is not None:
509
+ if self.state.ended:
510
+ raise StoreEnded("The SQL server ended the Preview transaction.")
511
+ if self.state.unsafe:
512
+ raise PreviewRollbackError(self.state.unsafe)
513
+ for alias, atomic in self.root.atomics:
514
+ connection = self.wrappers[alias]
515
+ if connection.closed_in_transaction or connection.atomic_blocks != [atomic]:
516
+ raise PreviewRollbackError("The handler changed the held Django transaction.")
517
+
518
+ def attach(self, scope: RequestScope, step: int) -> None:
519
+ self._check()
520
+ self.binding = self._bound()
521
+ self.binding.__enter__()
522
+ for alias in self.wrappers:
523
+ _raw(alias, "SAVEPOINT " + savepoint(step))
524
+ _raw(alias, "SAVEPOINT sendproof_step_proof")
525
+ self.state = _State(self.provider.aliases, rollback=True, safe_procedures=self.provider.safe_procedures)
526
+ self.state.install_wrappers()
527
+ scope.extensions[STATE_KEY] = self.state
528
+
529
+ def collect(self, scope: RequestScope, step: int) -> None:
530
+ self._check()
531
+ for alias, connection in self.wrappers.items():
532
+ if connection.needs_rollback:
533
+ raise StepFailed("The Preview statement failed inside Django's transaction.")
534
+ try:
535
+ _raw(alias, "RELEASE SAVEPOINT sendproof_step_proof")
536
+ except Exception as error:
537
+ if getattr(error, "sqlstate", getattr(error, "pgcode", None)) == "25P02":
538
+ raise StepFailed("The Preview statement failed inside PostgreSQL.") from error
539
+ raise
540
+ scope.store_changes[:0] = self.state.changes
541
+ scope.store_changes_truncated |= self.state.changes_truncated
542
+
543
+ def detach(self, scope: RequestScope) -> None:
544
+ if self.binding is not None:
545
+ try:
546
+ if self.state is not None:
547
+ self.state.finished = True
548
+ self.state.remove_wrappers()
549
+ finally:
550
+ binding, self.binding = self.binding, None
551
+ binding.__exit__(None, None, None)
552
+
553
+ def rewind(self, step: int) -> None:
554
+ self._check()
555
+ with self._bound():
556
+ for alias, connection in self.wrappers.items():
557
+ _raw(alias, "ROLLBACK TO SAVEPOINT " + savepoint(step))
558
+ _raw(alias, "RELEASE SAVEPOINT " + savepoint(step))
559
+ connection.set_rollback(False)
560
+
561
+ def _close_connections(self) -> None:
562
+ errors = []
563
+ for connection in self.wrappers.values():
564
+ try:
565
+ connection.close()
566
+ except Exception as error:
567
+ errors.append(error)
568
+ finally:
569
+ connection.dec_thread_sharing()
570
+ if errors:
571
+ raise errors[0]
572
+
573
+ def close(self) -> None:
574
+ with self._bound():
575
+ try:
576
+ session = _Session(self.root)
577
+ try:
578
+ session.rollback()
579
+ finally:
580
+ session.close()
581
+ finally:
582
+ self._close_connections()
File without changes
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: sendproof-django
3
+ Version: 0.1.0a2
4
+ Summary: Sendproof workbench, rollback previews and observed sends for Django, Django REST framework and Django Ninja, with Django ORM capture.
5
+ Project-URL: Homepage, https://github.com/mprync/sendproof/tree/main/adapters/python/django
6
+ Project-URL: Repository, https://github.com/mprync/sendproof
7
+ Project-URL: Issues, https://github.com/mprync/sendproof/issues
8
+ Project-URL: Changelog, https://github.com/mprync/sendproof/blob/main/CHANGELOG.md
9
+ Author: Sendproof contributors
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api-testing,django,django-ninja,djangorestframework,openapi,rollback,swagger,testing
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: Django
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Software Development :: Testing
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: django>=4.2
28
+ Requires-Dist: sendproof-core==0.1.0a2
29
+ Description-Content-Type: text/markdown
30
+
31
+ # sendproof-django
32
+
33
+ Serves the [Sendproof](../../spec/README.md) workbench from a Django project and runs rollback
34
+ **Preview** and **Observed Send** through Django's URL resolver, middleware and views. Works with
35
+ plain views, Django REST framework and Django Ninja, and captures changes through the Django ORM.
36
+
37
+ ```sh
38
+ pip install sendproof-django
39
+ ```
40
+
41
+ ```python
42
+ # settings.py
43
+ MIDDLEWARE = [
44
+ # ... sessions, authentication, your own middleware ...
45
+ "sendproof_django.middleware.SendproofMiddleware", # last
46
+ ]
47
+
48
+ SENDPROOF = {
49
+ "ENVIRONMENT": "Development", # off in any environment not listed
50
+ "PROVIDER": "sendproof_django.DjangoOrmPreview", # opt in to rollback previews
51
+ "OPENAPI_URL": "/api/openapi.json",
52
+ "AUTH_PROVIDERS": [{"label": "Password", "kind": "cookie", "url": "/auth/sign-in"}],
53
+ }
54
+ ```
55
+
56
+ The workbench is at `/sendproof/`. It is **off** unless `ENVIRONMENT` (default `$SENDPROOF_ENVIRONMENT`,
57
+ else `Production`) is in `ENVIRONMENTS` (default `["Development"]`).
58
+
59
+ ## Marking operations
60
+
61
+ ```python
62
+ from sendproof_django import preview
63
+
64
+ @preview(methods=["POST"]) # function view: methods accepted for previews
65
+ def create_item(request): ...
66
+
67
+ class Things(APIView): # Django REST framework (or any class-based view)
68
+ @preview # decorate the handler method
69
+ def post(self, request): ...
70
+
71
+ @api.post("/items") # Django Ninja: below the route decorator
72
+ @preview
73
+ def create_item(request, payload: ItemIn): ...
74
+ ```
75
+
76
+ Only marked operations are advertised and accepted. Without `methods`, a function view accepts
77
+ `POST`, `PUT`, `PATCH` and `DELETE`. Class-based handlers and Ninja operations use their own HTTP
78
+ methods. Routes written with `re_path` have no portable OpenAPI template and are not advertised.
79
+
80
+ ## Settings
81
+
82
+ | Key | Meaning |
83
+ | --- | --- |
84
+ | `PROVIDER` | `DjangoOrmPreview(using=("default",), database="label")`, an instance or dotted path. Without one, nothing is advertised and previews answer 503. |
85
+ | `IDENTITY` | `(request) -> Identity \| None` (callable or dotted path). Defaults to `request.user` when authenticated (subject = primary key). |
86
+ | `AUTHORIZE` | `(request, identity) -> bool`. Optional workbench policy (401/403). |
87
+ | `ENVIRONMENT`, `ENVIRONMENTS` | Where the workbench is on. |
88
+ | `API_NAME`, `OPENAPI_URL`, `DOCUMENTS`, `AUTH_PROVIDERS`, `FIELD_MODULES` | Discovery. `OPENAPI_URL` defaults to `/openapi.json`. |
89
+ | `INCLUDE_SQL_PARAMETER_VALUES` | Show SQL values (Development only by default). |
90
+ | `TRACE_TTL` | Seconds a trace is kept (default 300). |
91
+
92
+ Unknown keys raise `ValueError` so typos are not silently ignored.
93
+
94
+ ## How it works
95
+
96
+ A request to `/sendproof/_preview/<path>` with exactly `Prefer: tx=rollback` is resolved with your
97
+ URLconf, then a copy of the request is sent through the complete `MIDDLEWARE` chain and the real
98
+ view, in-process, with `transaction.atomic()` open on every enrolled database. Every middleware,
99
+ including path-based ones, sees the target path, and session changes stay on the copy, so they are
100
+ neither saved by the outer `SessionMiddleware` nor sent as a cookie. Sendproof checks again, last
101
+ in the chain, that the request still resolves to the marked view and method. The response is buffered (1 MiB cap),
102
+ the atomic blocks are rolled back and confirmed, and only then does the middleware answer with the
103
+ envelope. `Prefer: trace` on the original URL commits normally and adds `X-Sendproof-Trace`; the
104
+ same caller can fetch it from `/sendproof/_api/traces/{id}` until it expires.
105
+
106
+ - Commit semantics follow Django: a nested `atomic()` releases a savepoint, `transaction.on_commit`
107
+ callbacks are discarded with the rollback, and a handler that handles an `IntegrityError`
108
+ behaves as usual.
109
+ - A 401 or 403 is always a denial and never an envelope. Other statuses, including 409 and the
110
+ 400 or 422 your framework returns for invalid input, are the application's answer. An unhandled
111
+ exception becomes an unconfirmed 500.
112
+ - CSRF protection runs against the target view exactly as for a normal request. Sendproof
113
+ sends no CSRF token, so previews of views protected by it are rejected unless the view is
114
+ exempt or authenticates another way, as API views usually do.
115
+ - Mounted under a prefix (`SCRIPT_NAME`/`FORCE_SCRIPT_NAME`), discovery URLs include it. Django
116
+ Ninja prefixes OpenAPI paths with the script prefix; serve its schema with
117
+ `api.get_openapi_schema(path_prefix="/")` so the paths match the operations the workbench lists.
118
+
119
+ ## Change capture and coverage
120
+
121
+ Changes come from `pre_save`/`post_save`/`pre_delete`/`post_delete`: inserts, updates and deletes made
122
+ with `Model.save()`, `Model.objects.create()` and `Model.delete()`, including cascades the ORM
123
+ performs. The row before an update or delete is read from the database; that read is not logged.
124
+
125
+ - **Not captured (but rolled back):** `QuerySet.update()`, `bulk_create()`, `bulk_update()`, raw SQL,
126
+ triggers and cascades done by the database. Their SQL appears in the logs. Rows are never
127
+ synthesized.
128
+ - **Transaction-control SQL is refused before it is sent** and the Preview answers 500: `COMMIT`,
129
+ `ROLLBACK` (not `ROLLBACK TO SAVEPOINT`), `BEGIN`, `SET autocommit`, the internal
130
+ `sendproof_preview` savepoint, and on MySQL, MariaDB and Oracle the statements those databases
131
+ commit implicitly (DDL other than `TEMPORARY` tables, `LOCK TABLES`, `GRANT` and the rest of
132
+ MySQL's list). On MySQL and MariaDB `CALL` is refused too, because a procedure can commit,
133
+ unless you declare it safe by exact name (case-insensitive, no wildcards; the binding trusts the
134
+ declaration):
135
+
136
+ ```python
137
+ SENDPROOF = {"PROVIDER": lambda: DjangoOrmPreview(safe_procedures=["refresh_totals"]), ...}
138
+ ```
139
+
140
+ - **Backstop on every database:** the Preview opens its transaction with
141
+ `SAVEPOINT sendproof_preview` and checks, before rolling back, that it still exists. Any commit
142
+ erases it, so a Preview whose transaction was committed anyway (on the driver's own connection,
143
+ say, which then begins a new transaction) answers 500 without confirmation (the writes before
144
+ that commit stay).
145
+ - **Deadlocks on MySQL and MariaDB:** a deadlock (1213), or a lock wait timeout (1205) with
146
+ `innodb_rollback_on_timeout` on, rolls back the whole Preview transaction. The handler still gets
147
+ the original error; every later statement in that Preview except Django's own savepoint
148
+ rollbacks is refused before it is sent, and the Preview answers 500 without confirmation. The
149
+ lock wait timeout case shares the deadlock code path and is covered by unit tests only, because
150
+ `innodb_rollback_on_timeout` can be set only at server startup.
151
+ - Enrolled aliases share the request thread's connection. Work in other threads, other databases
152
+ you did not list, caches, files and other services are not rolled back.
153
+ - Synchronous views only. Async views and ASGI deployments are not tested.
154
+ - The inner response object is not closed during a preview, so Django's `request_finished`
155
+ connection cleanup cannot end the transaction early.
@@ -0,0 +1,10 @@
1
+ sendproof_django/__init__.py,sha256=tNBQUlVOhijC8_1f8bpa5kzqtRGFmJ4H02aP1X6OmqA,1924
2
+ sendproof_django/conf.py,sha256=C18gOm9ju6zx3Y9Ng8l2XvBKwo6Dd_B_zkJeX6bvDuA,4433
3
+ sendproof_django/discovery.py,sha256=WHDaskfIsBoWcglw7Unfo830HgMSp4CSV_8XQ-OiTuE,4929
4
+ sendproof_django/middleware.py,sha256=WJs2FEBBO47yMMUvJ_73exVEiJSbZ_MmkYvIKk0eIWM,13160
5
+ sendproof_django/orm.py,sha256=8DThwk5Z0alTkNFNjNbgBf9k-Q1BEQTgmAWXFOrbaVY,24793
6
+ sendproof_django/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ sendproof_django-0.1.0a2.dist-info/METADATA,sha256=A_NMdvVOGjKEvG7GuybMcc7Lsb20DX9_czgZ9FYvNHU,8527
8
+ sendproof_django-0.1.0a2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ sendproof_django-0.1.0a2.dist-info/licenses/LICENSE,sha256=FN_kx0TTA_TvTWeb5MzY7v1r6PwKKhW5msNFB2MeWSs,1079
10
+ sendproof_django-0.1.0a2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sendproof contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.