sendproof-core 0.1.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.
- sendproof_core/__init__.py +56 -0
- sendproof_core/assets.py +71 -0
- sendproof_core/capture.py +416 -0
- sendproof_core/effects.py +79 -0
- sendproof_core/identity.py +22 -0
- sendproof_core/jsonsafe.py +103 -0
- sendproof_core/limits.py +24 -0
- sendproof_core/marker.py +131 -0
- sendproof_core/options.py +129 -0
- sendproof_core/protocol.py +132 -0
- sendproof_core/provider.py +121 -0
- sendproof_core/py.typed +0 -0
- sendproof_core/redaction.py +88 -0
- sendproof_core/scope.py +146 -0
- sendproof_core/stores/__init__.py +119 -0
- sendproof_core/stores/base.py +99 -0
- sendproof_core/stores/cassandra_hook.py +173 -0
- sendproof_core/stores/classify.py +153 -0
- sendproof_core/stores/classify_batch_two.py +397 -0
- sendproof_core/stores/cosmos_hook.py +214 -0
- sendproof_core/stores/dynamodb_hook.py +214 -0
- sendproof_core/stores/elasticsearch_hook.py +248 -0
- sendproof_core/stores/firestore_hook.py +459 -0
- sendproof_core/stores/guard.py +205 -0
- sendproof_core/stores/mongo_hook.py +1406 -0
- sendproof_core/stores/redis_hook.py +536 -0
- sendproof_core/stores/tables.py +1486 -0
- sendproof_core/stores/versions.py +46 -0
- sendproof_core/sync_engine.py +308 -0
- sendproof_core/trace_store.py +92 -0
- sendproof_core/txguard.py +237 -0
- sendproof_core/ui/action-bar.js +91 -0
- sendproof_core/ui/api.js +239 -0
- sendproof_core/ui/app.css +848 -0
- sendproof_core/ui/app.js +742 -0
- sendproof_core/ui/autofill.js +137 -0
- sendproof_core/ui/code-copy.js +71 -0
- sendproof_core/ui/code-picker.js +149 -0
- sendproof_core/ui/commands.js +197 -0
- sendproof_core/ui/components.js +77 -0
- sendproof_core/ui/context-bar.js +82 -0
- sendproof_core/ui/copy.js +92 -0
- sendproof_core/ui/coverage-popover.js +35 -0
- sendproof_core/ui/crumb-fit.js +80 -0
- sendproof_core/ui/deprecation.js +164 -0
- sendproof_core/ui/display-settings.js +175 -0
- sendproof_core/ui/doc-diff.js +209 -0
- sendproof_core/ui/docs-view.js +347 -0
- sendproof_core/ui/favicon.png +0 -0
- sendproof_core/ui/favicon.svg +1 -0
- sendproof_core/ui/field-help.js +52 -0
- sendproof_core/ui/field-modules.js +23 -0
- sendproof_core/ui/fields/controls.js +179 -0
- sendproof_core/ui/fields/dom.js +36 -0
- sendproof_core/ui/fields/infer.js +71 -0
- sendproof_core/ui/fields/lookup-source.js +63 -0
- sendproof_core/ui/fields/lookup.js +285 -0
- sendproof_core/ui/fields/render.js +496 -0
- sendproof_core/ui/fields/select.js +175 -0
- sendproof_core/ui/fields/validate.js +363 -0
- sendproof_core/ui/fields/validation-formats.js +164 -0
- sendproof_core/ui/fields/validation-references.js +68 -0
- sendproof_core/ui/fields/validation-values.js +137 -0
- sendproof_core/ui/generate-menu.js +44 -0
- sendproof_core/ui/generate.js +184 -0
- sendproof_core/ui/header-editor.js +777 -0
- sendproof_core/ui/headers.js +188 -0
- sendproof_core/ui/highlight.js +257 -0
- sendproof_core/ui/history-popover.js +24 -0
- sendproof_core/ui/i18n.js +253 -0
- sendproof_core/ui/icons.js +87 -0
- sendproof_core/ui/index.html +70 -0
- sendproof_core/ui/issues.js +187 -0
- sendproof_core/ui/json-view.js +166 -0
- sendproof_core/ui/lang-icons.js +62 -0
- sendproof_core/ui/layout.js +262 -0
- sendproof_core/ui/listbox.js +334 -0
- sendproof_core/ui/locales/ar-capture.js +366 -0
- sendproof_core/ui/locales/ar-stores.js +116 -0
- sendproof_core/ui/locales/ar.js +561 -0
- sendproof_core/ui/locales/cs-capture.js +442 -0
- sendproof_core/ui/locales/cs-stores.js +116 -0
- sendproof_core/ui/locales/cs.js +689 -0
- sendproof_core/ui/locales/da-capture.js +347 -0
- sendproof_core/ui/locales/da-stores.js +116 -0
- sendproof_core/ui/locales/da.js +522 -0
- sendproof_core/ui/locales/de-capture.js +347 -0
- sendproof_core/ui/locales/de-stores.js +116 -0
- sendproof_core/ui/locales/de.js +519 -0
- sendproof_core/ui/locales/el-capture.js +347 -0
- sendproof_core/ui/locales/el-stores.js +116 -0
- sendproof_core/ui/locales/el.js +520 -0
- sendproof_core/ui/locales/en-capture.js +349 -0
- sendproof_core/ui/locales/en-stores.js +95 -0
- sendproof_core/ui/locales/en.js +522 -0
- sendproof_core/ui/locales/es-capture.js +353 -0
- sendproof_core/ui/locales/es-stores.js +116 -0
- sendproof_core/ui/locales/es.js +525 -0
- sendproof_core/ui/locales/fa-capture.js +348 -0
- sendproof_core/ui/locales/fa-stores.js +116 -0
- sendproof_core/ui/locales/fa.js +521 -0
- sendproof_core/ui/locales/fi-capture.js +347 -0
- sendproof_core/ui/locales/fi-stores.js +116 -0
- sendproof_core/ui/locales/fi.js +523 -0
- sendproof_core/ui/locales/fr-capture.js +353 -0
- sendproof_core/ui/locales/fr-stores.js +116 -0
- sendproof_core/ui/locales/fr.js +525 -0
- sendproof_core/ui/locales/he-capture.js +358 -0
- sendproof_core/ui/locales/he-stores.js +116 -0
- sendproof_core/ui/locales/he.js +529 -0
- sendproof_core/ui/locales/hi-capture.js +348 -0
- sendproof_core/ui/locales/hi-stores.js +116 -0
- sendproof_core/ui/locales/hi.js +523 -0
- sendproof_core/ui/locales/id-capture.js +347 -0
- sendproof_core/ui/locales/id-stores.js +116 -0
- sendproof_core/ui/locales/id.js +521 -0
- sendproof_core/ui/locales/it-capture.js +361 -0
- sendproof_core/ui/locales/it-stores.js +116 -0
- sendproof_core/ui/locales/it.js +523 -0
- sendproof_core/ui/locales/ja-capture.js +346 -0
- sendproof_core/ui/locales/ja-stores.js +116 -0
- sendproof_core/ui/locales/ja.js +521 -0
- sendproof_core/ui/locales/ko-capture.js +346 -0
- sendproof_core/ui/locales/ko-stores.js +116 -0
- sendproof_core/ui/locales/ko.js +522 -0
- sendproof_core/ui/locales/nb-capture.js +349 -0
- sendproof_core/ui/locales/nb-stores.js +116 -0
- sendproof_core/ui/locales/nb.js +521 -0
- sendproof_core/ui/locales/nl-capture.js +355 -0
- sendproof_core/ui/locales/nl-stores.js +116 -0
- sendproof_core/ui/locales/nl.js +520 -0
- sendproof_core/ui/locales/pl-capture.js +432 -0
- sendproof_core/ui/locales/pl-stores.js +116 -0
- sendproof_core/ui/locales/pl.js +528 -0
- sendproof_core/ui/locales/pt-BR-capture.js +350 -0
- sendproof_core/ui/locales/pt-BR-stores.js +116 -0
- sendproof_core/ui/locales/pt-BR.js +523 -0
- sendproof_core/ui/locales/pt-PT-capture.js +350 -0
- sendproof_core/ui/locales/pt-PT-stores.js +116 -0
- sendproof_core/ui/locales/pt-PT.js +523 -0
- sendproof_core/ui/locales/ru-capture.js +437 -0
- sendproof_core/ui/locales/ru-stores.js +116 -0
- sendproof_core/ui/locales/ru.js +624 -0
- sendproof_core/ui/locales/sv-capture.js +349 -0
- sendproof_core/ui/locales/sv-stores.js +116 -0
- sendproof_core/ui/locales/sv.js +518 -0
- sendproof_core/ui/locales/th-capture.js +347 -0
- sendproof_core/ui/locales/th-stores.js +116 -0
- sendproof_core/ui/locales/th.js +521 -0
- sendproof_core/ui/locales/tr-capture.js +348 -0
- sendproof_core/ui/locales/tr-stores.js +116 -0
- sendproof_core/ui/locales/tr.js +521 -0
- sendproof_core/ui/locales/uk-capture.js +442 -0
- sendproof_core/ui/locales/uk-stores.js +116 -0
- sendproof_core/ui/locales/uk.js +630 -0
- sendproof_core/ui/locales/vi-capture.js +346 -0
- sendproof_core/ui/locales/vi-stores.js +116 -0
- sendproof_core/ui/locales/vi.js +523 -0
- sendproof_core/ui/locales/zh-Hans-capture.js +347 -0
- sendproof_core/ui/locales/zh-Hans-stores.js +116 -0
- sendproof_core/ui/locales/zh-Hans.js +523 -0
- sendproof_core/ui/locales/zh-Hant-capture.js +346 -0
- sendproof_core/ui/locales/zh-Hant-stores.js +116 -0
- sendproof_core/ui/locales/zh-Hant.js +522 -0
- sendproof_core/ui/manifest.json +866 -0
- sendproof_core/ui/markdown.js +39 -0
- sendproof_core/ui/model-view.js +182 -0
- sendproof_core/ui/navigation.js +233 -0
- sendproof_core/ui/operation-header.js +76 -0
- sendproof_core/ui/operations.js +7 -0
- sendproof_core/ui/overview-view.js +63 -0
- sendproof_core/ui/personas.js +59 -0
- sendproof_core/ui/popover.js +71 -0
- sendproof_core/ui/preview-false.js +108 -0
- sendproof_core/ui/request-editor.js +496 -0
- sendproof_core/ui/response-metadata.js +354 -0
- sendproof_core/ui/response-viewer.js +618 -0
- sendproof_core/ui/result-blocked.js +155 -0
- sendproof_core/ui/result-capture.js +25 -0
- sendproof_core/ui/result-database.js +185 -0
- sendproof_core/ui/result-effects.js +176 -0
- sendproof_core/ui/result-headers.js +106 -0
- sendproof_core/ui/result-logs.js +408 -0
- sendproof_core/ui/result-states.js +213 -0
- sendproof_core/ui/results.js +371 -0
- sendproof_core/ui/router.js +118 -0
- sendproof_core/ui/schema-model.js +336 -0
- sendproof_core/ui/schema-tree.js +344 -0
- sendproof_core/ui/schema.js +397 -0
- sendproof_core/ui/security.js +31 -0
- sendproof_core/ui/seeded-menu.js +69 -0
- sendproof_core/ui/settings.js +93 -0
- sendproof_core/ui/shortcuts-sheet.js +73 -0
- sendproof_core/ui/shortcuts.js +190 -0
- sendproof_core/ui/sidebar.js +289 -0
- sendproof_core/ui/signin.js +259 -0
- sendproof_core/ui/snippets.js +530 -0
- sendproof_core/ui/store-marks.js +47 -0
- sendproof_core/ui/stores.js +131 -0
- sendproof_core/ui/styles.css +971 -0
- sendproof_core/ui/toggletip.js +53 -0
- sendproof_core/ui/uuid.js +10 -0
- sendproof_core/ui/view.js +122 -0
- sendproof_core/ui/views.css +653 -0
- sendproof_core/workbench.py +310 -0
- sendproof_core-0.1.0a1.dist-info/METADATA +116 -0
- sendproof_core-0.1.0a1.dist-info/RECORD +209 -0
- sendproof_core-0.1.0a1.dist-info/WHEEL +4 -0
- sendproof_core-0.1.0a1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Bounded conversion of host-provided values to JSON-compatible data."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import dataclasses
|
|
7
|
+
import datetime as dt
|
|
8
|
+
import decimal
|
|
9
|
+
import enum
|
|
10
|
+
import ipaddress
|
|
11
|
+
import json
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from . import limits
|
|
16
|
+
|
|
17
|
+
_MISSING = object()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Unserializable(Exception):
|
|
21
|
+
"""Raised when a value cannot be represented within the capture limits."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def to_jsonable(value: Any, depth: int = 0) -> Any:
|
|
25
|
+
"""Convert ``value`` to JSON-compatible data or raise :class:`Unserializable`.
|
|
26
|
+
|
|
27
|
+
Strings, collections and nesting are bounded by :mod:`sendproof_core.limits`.
|
|
28
|
+
Objects that expose ``model_dump`` (pydantic) or are dataclasses are expanded.
|
|
29
|
+
"""
|
|
30
|
+
if depth > limits.MAX_DEPTH:
|
|
31
|
+
raise Unserializable("depth")
|
|
32
|
+
if value is None or isinstance(value, (bool, int)):
|
|
33
|
+
return value
|
|
34
|
+
if isinstance(value, float):
|
|
35
|
+
if value != value or value in (float("inf"), float("-inf")):
|
|
36
|
+
return str(value)
|
|
37
|
+
return value
|
|
38
|
+
if isinstance(value, str):
|
|
39
|
+
if len(value) > limits.TEXT:
|
|
40
|
+
raise Unserializable("string")
|
|
41
|
+
return value
|
|
42
|
+
if isinstance(value, enum.Enum):
|
|
43
|
+
return to_jsonable(value.value, depth + 1)
|
|
44
|
+
if isinstance(value, (dt.datetime, dt.date, dt.time)):
|
|
45
|
+
return value.isoformat()
|
|
46
|
+
if isinstance(value, dt.timedelta):
|
|
47
|
+
return str(value)
|
|
48
|
+
if isinstance(value, (decimal.Decimal, uuid.UUID, ipaddress.IPv4Address, ipaddress.IPv6Address)):
|
|
49
|
+
return str(value)
|
|
50
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
51
|
+
raw = bytes(value)[: limits.TEXT // 2]
|
|
52
|
+
return raw.hex()
|
|
53
|
+
if isinstance(value, dict):
|
|
54
|
+
if len(value) > limits.PARAMETERS:
|
|
55
|
+
raise Unserializable("object")
|
|
56
|
+
result = {}
|
|
57
|
+
for key, item in value.items():
|
|
58
|
+
name = key if isinstance(key, str) else str(key)
|
|
59
|
+
if len(name) > limits.NAME:
|
|
60
|
+
raise Unserializable("name")
|
|
61
|
+
result[name] = to_jsonable(item, depth + 1)
|
|
62
|
+
return result
|
|
63
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
64
|
+
if len(value) > limits.PARAMETERS:
|
|
65
|
+
raise Unserializable("array")
|
|
66
|
+
return [to_jsonable(item, depth + 1) for item in value]
|
|
67
|
+
dump = getattr(value, "model_dump", None)
|
|
68
|
+
if callable(dump):
|
|
69
|
+
return to_jsonable(dump(mode="json"), depth + 1)
|
|
70
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
71
|
+
return to_jsonable(dataclasses.asdict(value), depth + 1)
|
|
72
|
+
raise Unserializable(type(value).__name__)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def snapshot(value: Any) -> Any:
|
|
76
|
+
"""Return a bounded JSON-compatible copy of ``value`` or ``_MISSING`` when it does not fit."""
|
|
77
|
+
try:
|
|
78
|
+
data = to_jsonable(value)
|
|
79
|
+
if len(json.dumps(data, separators=(",", ":"))) > limits.PAYLOAD_BYTES:
|
|
80
|
+
return _MISSING
|
|
81
|
+
return data
|
|
82
|
+
except (Unserializable, TypeError, ValueError, RecursionError):
|
|
83
|
+
return _MISSING
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def is_missing(value: Any) -> bool:
|
|
87
|
+
"""Whether :func:`snapshot` rejected the value."""
|
|
88
|
+
return value is _MISSING
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def body_from_bytes(content_type: str, payload: bytes) -> Any:
|
|
92
|
+
"""Decode a captured response body for the preview envelope."""
|
|
93
|
+
if not payload:
|
|
94
|
+
return None
|
|
95
|
+
media = content_type.split(";", 1)[0].strip().lower()
|
|
96
|
+
if media == "application/json" or media.endswith("+json"):
|
|
97
|
+
try:
|
|
98
|
+
return json.loads(payload)
|
|
99
|
+
except ValueError:
|
|
100
|
+
return payload.decode("utf-8", errors="replace")
|
|
101
|
+
if not media or media.startswith("text/"):
|
|
102
|
+
return payload.decode("utf-8", errors="replace")
|
|
103
|
+
return base64.b64encode(payload).decode("ascii")
|
sendproof_core/limits.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Capture limits shared by every adapter.
|
|
2
|
+
|
|
3
|
+
The values match the .NET adapters so that one UI renders every binding.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
LOGS = 500
|
|
9
|
+
EFFECTS = 100
|
|
10
|
+
CHANGES = 200
|
|
11
|
+
PROPERTIES = 32
|
|
12
|
+
PARAMETERS = 64
|
|
13
|
+
NAME = 256
|
|
14
|
+
TEXT = 4096
|
|
15
|
+
PAYLOAD_BYTES = 16 * 1024
|
|
16
|
+
LOG_BUDGET = 128 * 1024
|
|
17
|
+
CHANGE_BUDGET = 128 * 1024
|
|
18
|
+
MAX_DEPTH = 16
|
|
19
|
+
RESPONSE_BYTES = 1024 * 1024
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def clip(value: str, maximum: int = TEXT) -> str:
|
|
23
|
+
"""Truncate ``value`` to ``maximum`` characters."""
|
|
24
|
+
return value if len(value) <= maximum else value[:maximum]
|
sendproof_core/marker.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""The ``@preview`` marker that opts a view or endpoint into rollback previews and observed sends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import inspect
|
|
7
|
+
import types
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Callable, Iterable, TypeVar
|
|
10
|
+
|
|
11
|
+
from .scope import current_scope
|
|
12
|
+
|
|
13
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
14
|
+
MARKER = "__sendproof_preview__"
|
|
15
|
+
METHODS = "__sendproof_methods__"
|
|
16
|
+
UNAVAILABLE = "__sendproof_unavailable__"
|
|
17
|
+
WRITE_METHODS = ("DELETE", "PATCH", "POST", "PUT")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def enter() -> None:
|
|
21
|
+
"""Record that routing, authentication and validation passed and the handler runs."""
|
|
22
|
+
scope = current_scope()
|
|
23
|
+
if scope is not None:
|
|
24
|
+
scope.entered = True
|
|
25
|
+
scope.capture.handler_started()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Unavailable:
|
|
30
|
+
"""An operation marked ``preview: false``: Preview refuses it, Send still runs it."""
|
|
31
|
+
|
|
32
|
+
#: The sentence the workbench shows before anyone tries.
|
|
33
|
+
reason: str
|
|
34
|
+
#: Store ids the operation writes to, such as ``("redis",)``.
|
|
35
|
+
stores: tuple[str, ...] = ()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def unavailable_reason(reason: str | None, stores: Iterable[str]) -> str:
|
|
39
|
+
"""The published reason: the author's own, else one built from the first named store."""
|
|
40
|
+
from .stores.guard import write_reason
|
|
41
|
+
|
|
42
|
+
if reason is not None and reason.strip():
|
|
43
|
+
return reason
|
|
44
|
+
names = list(stores)
|
|
45
|
+
return write_reason(names[0]) if names else "Preview unavailable: this operation is marked preview: false"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def mark(endpoint: F, methods: tuple[str, ...] | None = None, unavailable: Unavailable | None = None) -> F:
|
|
49
|
+
"""Wrap a function so that calling it records handler entry, and tag it as previewable.
|
|
50
|
+
|
|
51
|
+
The wrapper keeps the signature (``functools.wraps``), stays a coroutine function when the
|
|
52
|
+
original is one, and shares the original's module globals so that frameworks resolving
|
|
53
|
+
string annotations (``from __future__ import annotations``) still find your types.
|
|
54
|
+
"""
|
|
55
|
+
record_entry = enter # a closure variable: the wrapper must not need its own module globals
|
|
56
|
+
|
|
57
|
+
if inspect.iscoroutinefunction(endpoint):
|
|
58
|
+
|
|
59
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
60
|
+
record_entry()
|
|
61
|
+
return await endpoint(*args, **kwargs)
|
|
62
|
+
|
|
63
|
+
else:
|
|
64
|
+
|
|
65
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any: # type: ignore[misc]
|
|
66
|
+
record_entry()
|
|
67
|
+
return endpoint(*args, **kwargs)
|
|
68
|
+
|
|
69
|
+
globals_ = getattr(endpoint, "__globals__", None)
|
|
70
|
+
if globals_ is not None:
|
|
71
|
+
clone = types.FunctionType(wrapper.__code__, globals_, wrapper.__name__, wrapper.__defaults__, wrapper.__closure__)
|
|
72
|
+
clone.__kwdefaults__ = wrapper.__kwdefaults__
|
|
73
|
+
wrapper = clone
|
|
74
|
+
functools.update_wrapper(wrapper, endpoint)
|
|
75
|
+
setattr(wrapper, MARKER, True)
|
|
76
|
+
if methods is not None:
|
|
77
|
+
setattr(wrapper, METHODS, tuple(m.upper() for m in methods))
|
|
78
|
+
if unavailable is not None:
|
|
79
|
+
setattr(wrapper, UNAVAILABLE, unavailable)
|
|
80
|
+
return wrapper # type: ignore[return-value]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def apply_marker(
|
|
84
|
+
target: Any, enabled: Any = True, *, reason: str | None = None, stores: Iterable[str] | None = None,
|
|
85
|
+
methods: Iterable[str] | None = None,
|
|
86
|
+
) -> Any:
|
|
87
|
+
"""Implement the framework ``preview`` decorators, which share one calling convention.
|
|
88
|
+
|
|
89
|
+
``@preview`` marks a handler as previewable; ``@preview(False, reason="...", stores=["redis"])``
|
|
90
|
+
marks it ``preview: false`` instead: the workbench shows "Preview unavailable" with the reason
|
|
91
|
+
before anyone tries, a Preview of it is refused (never confirmed) without running the handler,
|
|
92
|
+
and Send still runs it. ``target`` is the decorated function, or the flag when written with
|
|
93
|
+
arguments, in which case a decorator is returned.
|
|
94
|
+
"""
|
|
95
|
+
kept = tuple(methods) if methods else None
|
|
96
|
+
if callable(target) and enabled is True and reason is None and stores is None:
|
|
97
|
+
return mark(target, kept)
|
|
98
|
+
flag = target if not callable(target) else enabled
|
|
99
|
+
if not isinstance(flag, bool):
|
|
100
|
+
raise TypeError("preview takes a handler, or True or False followed by keyword options.")
|
|
101
|
+
names = tuple(stores or ())
|
|
102
|
+
if any(not isinstance(name, str) or not name for name in names):
|
|
103
|
+
raise TypeError("stores takes store ids such as 'redis'.")
|
|
104
|
+
|
|
105
|
+
def decorate(handler: F) -> F:
|
|
106
|
+
if flag:
|
|
107
|
+
return mark(handler, kept)
|
|
108
|
+
return mark(handler, kept, Unavailable(unavailable_reason(reason, names), names))
|
|
109
|
+
|
|
110
|
+
return decorate if not callable(target) else decorate(target)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def is_marked(endpoint: Any) -> bool:
|
|
114
|
+
"""Whether a callable carries the preview marker (previewable, or marked ``preview: false``)."""
|
|
115
|
+
return bool(getattr(endpoint, MARKER, False))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def unavailable_info(endpoint: Any) -> Unavailable | None:
|
|
119
|
+
"""The ``preview: false`` mark of a callable, if it has one."""
|
|
120
|
+
found = getattr(endpoint, UNAVAILABLE, None)
|
|
121
|
+
return found if isinstance(found, Unavailable) else None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def is_previewable(endpoint: Any) -> bool:
|
|
125
|
+
"""Whether a Preview may run the callable: marked, and not marked ``preview: false``."""
|
|
126
|
+
return is_marked(endpoint) and unavailable_info(endpoint) is None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def marked_methods(endpoint: Any) -> tuple[str, ...]:
|
|
130
|
+
"""HTTP methods a marked callable accepts for previews (write methods by default)."""
|
|
131
|
+
return tuple(getattr(endpoint, METHODS, WRITE_METHODS))
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Configuration shared by every framework adapter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Callable, Iterable
|
|
9
|
+
|
|
10
|
+
from .identity import Identity
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _is_local_url(url: str) -> bool:
|
|
14
|
+
from urllib.parse import unquote
|
|
15
|
+
|
|
16
|
+
path = url.split("?", 1)[0]
|
|
17
|
+
decoded = unquote(path)
|
|
18
|
+
return (
|
|
19
|
+
path.startswith("/")
|
|
20
|
+
and not path.startswith("//")
|
|
21
|
+
and "\\" not in url
|
|
22
|
+
and "#" not in url
|
|
23
|
+
and not any(c.isspace() or ord(c) < 32 for c in url)
|
|
24
|
+
and not decoded.startswith("//")
|
|
25
|
+
and "\\" not in decoded
|
|
26
|
+
# Browsers treat "%2e%2e" as "..", so dot segments are checked after decoding.
|
|
27
|
+
and not any(part in (".", "..") for part in decoded.split("/"))
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def require_local_url(url: str) -> str:
|
|
32
|
+
"""Validate an application-relative, same-origin URL."""
|
|
33
|
+
if not isinstance(url, str) or not _is_local_url(url):
|
|
34
|
+
raise ValueError("Use an application-relative, same-origin path such as '/openapi.json'.")
|
|
35
|
+
return url
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def require_display_label(label: str) -> str:
|
|
39
|
+
"""Validate a public database label: a bare name such as ``PostgreSQL``.
|
|
40
|
+
|
|
41
|
+
Connection strings, URLs, hosts, credentials and file paths are refused so that a
|
|
42
|
+
misconfigured label never publishes them in discovery.
|
|
43
|
+
"""
|
|
44
|
+
if (
|
|
45
|
+
not isinstance(label, str)
|
|
46
|
+
or not label.strip()
|
|
47
|
+
or len(label) > 128
|
|
48
|
+
or any(c in label for c in "/\\@=;:?#")
|
|
49
|
+
or any(ord(c) < 32 for c in label)
|
|
50
|
+
):
|
|
51
|
+
raise ValueError("Use a bare display name for the database label, such as 'PostgreSQL'.")
|
|
52
|
+
return label
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class AuthProvider:
|
|
57
|
+
"""A sign-in integration advertised in discovery."""
|
|
58
|
+
|
|
59
|
+
label: str
|
|
60
|
+
kind: str
|
|
61
|
+
url: str | None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class OpenApiDocument:
|
|
66
|
+
"""A named OpenAPI document."""
|
|
67
|
+
|
|
68
|
+
name: str
|
|
69
|
+
url: str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class BenchOptions:
|
|
74
|
+
"""Framework-neutral options.
|
|
75
|
+
|
|
76
|
+
The workbench is off unless ``environment`` is one of ``environments``. With no
|
|
77
|
+
``environment`` the value of ``SENDPROOF_ENVIRONMENT`` is used, and without that the
|
|
78
|
+
environment is ``Production``.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
api_name: str | None = None
|
|
82
|
+
openapi_url: str | None = None
|
|
83
|
+
documents: list[OpenApiDocument] = field(default_factory=list)
|
|
84
|
+
environment: str | None = None
|
|
85
|
+
environments: tuple[str, ...] = ("Development",)
|
|
86
|
+
auth_providers: list[AuthProvider] = field(default_factory=list)
|
|
87
|
+
field_modules: list[str] = field(default_factory=list)
|
|
88
|
+
include_sql_parameter_values: bool | None = None
|
|
89
|
+
trace_ttl: float = 300.0
|
|
90
|
+
clock: Callable[[], float] = time.monotonic
|
|
91
|
+
identity: Callable[..., Identity | None] | None = None
|
|
92
|
+
#: The web framework serving the workbench, published as capabilities ``binding.framework``
|
|
93
|
+
#: so the workbench shows the ``preview: false`` snippet in the host's own language.
|
|
94
|
+
framework: str | None = None
|
|
95
|
+
|
|
96
|
+
def __post_init__(self) -> None:
|
|
97
|
+
if self.environment is None:
|
|
98
|
+
self.environment = os.environ.get("SENDPROOF_ENVIRONMENT") or "Production"
|
|
99
|
+
self.environments = tuple(self.environments)
|
|
100
|
+
if self.openapi_url is not None:
|
|
101
|
+
require_local_url(self.openapi_url)
|
|
102
|
+
for url in self.field_modules:
|
|
103
|
+
require_local_url(url)
|
|
104
|
+
for document in self.documents:
|
|
105
|
+
require_local_url(document.url)
|
|
106
|
+
for provider in self.auth_providers:
|
|
107
|
+
if provider.url is not None:
|
|
108
|
+
require_local_url(provider.url)
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def enabled(self) -> bool:
|
|
112
|
+
"""Whether the workbench and previews are available in this environment."""
|
|
113
|
+
assert self.environment is not None
|
|
114
|
+
return any(self.environment.lower() == name.lower() for name in self.environments)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def show_sql_values(self) -> bool:
|
|
118
|
+
"""Whether SQL parameter values are shown (Development by default)."""
|
|
119
|
+
if self.include_sql_parameter_values is not None:
|
|
120
|
+
return self.include_sql_parameter_values
|
|
121
|
+
return (self.environment or "").lower() == "development"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def normalize_environments(values: Iterable[str]) -> tuple[str, ...]:
|
|
125
|
+
"""Validate environment names."""
|
|
126
|
+
names = tuple(values)
|
|
127
|
+
if any(not isinstance(name, str) or not name.strip() for name in names):
|
|
128
|
+
raise ValueError("Environment names must be non-empty strings.")
|
|
129
|
+
return names
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Protocol v1 constants and request predicates, independent of any web framework."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Callable, Sequence
|
|
7
|
+
|
|
8
|
+
PREVIEW_PREFIX = "/sendproof/_preview"
|
|
9
|
+
BENCH_PREFIX = "/sendproof"
|
|
10
|
+
ROLLBACK_PREFERENCE = "tx=rollback"
|
|
11
|
+
TRACE_HEADER = "X-Sendproof-Trace"
|
|
12
|
+
PROTOCOL_VERSION = 1
|
|
13
|
+
|
|
14
|
+
#: Returns every value of a request header, case-insensitively.
|
|
15
|
+
HeaderGetter = Callable[[str], Sequence[str]]
|
|
16
|
+
|
|
17
|
+
# Hop-by-hop and private headers that never travel in a preview envelope.
|
|
18
|
+
PRIVATE_HEADERS = frozenset(
|
|
19
|
+
{"set-cookie", "location", "content-length", "transfer-encoding", "connection", "upgrade", "trailer"}
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def has_exact_preference(get: HeaderGetter) -> bool:
|
|
24
|
+
"""Whether ``Prefer`` is exactly one ``tx=rollback`` value."""
|
|
25
|
+
values = get("prefer")
|
|
26
|
+
return len(values) == 1 and values[0].strip().lower() == ROLLBACK_PREFERENCE
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def requests_rollback(get: HeaderGetter) -> bool:
|
|
30
|
+
"""Whether any ``Prefer`` token asks for ``tx=rollback``."""
|
|
31
|
+
for value in get("prefer"):
|
|
32
|
+
for part in value.replace(";", ",").split(","):
|
|
33
|
+
name, _, setting = part.partition("=")
|
|
34
|
+
if name.strip().lower() == "tx" and setting.strip().strip('"').lower() == "rollback":
|
|
35
|
+
return True
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def requests_trace(get: HeaderGetter) -> bool:
|
|
40
|
+
"""Whether ``Prefer`` contains the ``trace`` token."""
|
|
41
|
+
for value in get("prefer"):
|
|
42
|
+
for part in value.split(","):
|
|
43
|
+
if part.split(";", 1)[0].strip().lower() == "trace":
|
|
44
|
+
return True
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def is_same_origin(get: HeaderGetter, scheme: str, host: str) -> bool:
|
|
49
|
+
"""Reject cross-site fetches and mismatching ``Origin`` headers."""
|
|
50
|
+
site = get("sec-fetch-site")
|
|
51
|
+
if site and site[0].lower() == "cross-site":
|
|
52
|
+
return False
|
|
53
|
+
origins = get("origin")
|
|
54
|
+
if not origins:
|
|
55
|
+
return True
|
|
56
|
+
if len(origins) != 1:
|
|
57
|
+
return False
|
|
58
|
+
origin = _normalize_origin(origins[0])
|
|
59
|
+
# "Origin: null" and malformed values never match, even when the Host header is malformed too.
|
|
60
|
+
return origin is not None and origin == _normalize_origin(f"{scheme}://{host}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _normalize_origin(value: str) -> str | None:
|
|
64
|
+
from urllib.parse import urlsplit
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
parts = urlsplit(value.strip())
|
|
68
|
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
69
|
+
return None
|
|
70
|
+
if parts.username or parts.password or parts.path not in ("", "/") or parts.query or parts.fragment:
|
|
71
|
+
return None
|
|
72
|
+
port = parts.port or (443 if parts.scheme == "https" else 80)
|
|
73
|
+
except ValueError:
|
|
74
|
+
return None
|
|
75
|
+
return f"{parts.scheme}://{parts.hostname.lower()}:{port}"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def is_valid_preview_target(target: str) -> bool:
|
|
79
|
+
"""Whether the path after ``/sendproof/_preview`` is a safe in-app target."""
|
|
80
|
+
from urllib.parse import unquote
|
|
81
|
+
|
|
82
|
+
if not target or not target.startswith("/") or target.startswith("//"):
|
|
83
|
+
return False
|
|
84
|
+
decoded = unquote(target)
|
|
85
|
+
if decoded.startswith("//") or "\\" in decoded or any(ord(c) < 32 or ord(c) == 127 for c in decoded):
|
|
86
|
+
return False
|
|
87
|
+
if any(segment in (".", "..") for segment in decoded.split("/")):
|
|
88
|
+
return False
|
|
89
|
+
return not (target == BENCH_PREFIX or target.startswith(BENCH_PREFIX + "/"))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def problem(status: int, title: str) -> tuple[int, list[tuple[str, str]], bytes]:
|
|
93
|
+
"""Build an ``application/problem+json`` response."""
|
|
94
|
+
body = json.dumps({"status": status, "title": title}, separators=(",", ":")).encode()
|
|
95
|
+
return status, [("content-type", "application/problem+json"), ("cache-control", "no-store")], body
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def classify_unexecuted(status: int) -> tuple[int, str]:
|
|
99
|
+
"""Map the status of a request that never reached the handler to a transport rejection."""
|
|
100
|
+
titles = {
|
|
101
|
+
401: "Authentication is required for this preview.",
|
|
102
|
+
403: "This preview is forbidden.",
|
|
103
|
+
404: "The preview target was not found for this method.",
|
|
104
|
+
405: "The preview target was not found for this method.",
|
|
105
|
+
503: "Preview requires one available preview provider.",
|
|
106
|
+
}
|
|
107
|
+
if 300 <= status < 400:
|
|
108
|
+
return 401, "Preview redirects are disabled. Sign in through the workbench first."
|
|
109
|
+
if status in titles:
|
|
110
|
+
return status, titles[status]
|
|
111
|
+
if 400 <= status < 500 and status != 409:
|
|
112
|
+
return status, "The host rejected the preview request."
|
|
113
|
+
return 409, "This operation is unavailable for preview."
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Statuses returned by the framework for a request that fails validation before the endpoint
|
|
117
|
+
# runs. They describe the application's answer, so they stay inside the envelope.
|
|
118
|
+
VALIDATION_STATUSES = frozenset({400, 422})
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# A 401 or 403 is treated as an authentication or authorization denial even when the handler
|
|
122
|
+
# produced it, because the transport cannot tell the two apart. Denials never yield an envelope.
|
|
123
|
+
DENIAL_STATUSES = frozenset({401, 403})
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def is_application_response(entered: bool, status: int) -> bool:
|
|
127
|
+
"""Whether a response is the application's own answer rather than a transport-level denial.
|
|
128
|
+
|
|
129
|
+
It is when the handler was entered, or when the framework rejected the request body
|
|
130
|
+
(400 or 422) before the handler; a 401 or 403 never is.
|
|
131
|
+
"""
|
|
132
|
+
return status not in DENIAL_STATUSES and (entered or status in VALIDATION_STATUSES)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Contracts implemented by data-layer integrations such as ``sendproof-sqlalchemy``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextvars
|
|
7
|
+
import functools
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, Callable, TypeVar
|
|
11
|
+
|
|
12
|
+
from .scope import RequestScope
|
|
13
|
+
|
|
14
|
+
T = TypeVar("T")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PreviewRollbackError(RuntimeError):
|
|
18
|
+
"""Raised by a session that cannot confirm that all writes were rolled back."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PreviewUnavailable(RuntimeError):
|
|
22
|
+
"""Raised by ``begin`` when the data layer cannot enroll the operation."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class PreviewChange:
|
|
27
|
+
"""One captured row change. Values must be JSON-compatible."""
|
|
28
|
+
|
|
29
|
+
operation: str
|
|
30
|
+
table: str
|
|
31
|
+
key: Any
|
|
32
|
+
before: dict[str, Any] | None
|
|
33
|
+
after: dict[str, Any] | None
|
|
34
|
+
#: Store id (``mongodb``) for a data-store change; ``None`` for the SQL database.
|
|
35
|
+
store: str | None = None
|
|
36
|
+
#: The database holding the collection or table, for a data-store change.
|
|
37
|
+
namespace: str | None = None
|
|
38
|
+
#: ``"upsert"`` or ``"replace"`` when the operation alone hides how the change was made.
|
|
39
|
+
via: str | None = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class PreviewSession(ABC):
|
|
43
|
+
"""Transaction scope and change capture for one preview request.
|
|
44
|
+
|
|
45
|
+
``begin`` must be cheap and synchronous, and it must not touch the database until the
|
|
46
|
+
application does. The adapter calls :meth:`rollback` after the handler finished, then
|
|
47
|
+
:meth:`close` on every path, including failures.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
@abstractmethod
|
|
52
|
+
def changes(self) -> list[PreviewChange]:
|
|
53
|
+
"""Captured changes, available after rollback until close."""
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def changes_truncated(self) -> bool:
|
|
57
|
+
"""Whether changes were omitted because of a capture limit."""
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
@abstractmethod
|
|
61
|
+
def rollback(self) -> None:
|
|
62
|
+
"""Roll back all writes. Raise :class:`PreviewRollbackError` if that cannot be confirmed."""
|
|
63
|
+
|
|
64
|
+
@abstractmethod
|
|
65
|
+
def close(self) -> None:
|
|
66
|
+
"""Release every resource, including those partially acquired. Must be idempotent."""
|
|
67
|
+
|
|
68
|
+
async def arollback(self) -> None:
|
|
69
|
+
"""Async variant of :meth:`rollback`. The default runs it in a worker thread."""
|
|
70
|
+
await run_in_thread(self.rollback)
|
|
71
|
+
|
|
72
|
+
async def aclose(self) -> None:
|
|
73
|
+
"""Async variant of :meth:`close`. The default runs it in a worker thread."""
|
|
74
|
+
await run_in_thread(self.close)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class PreviewObservation(ABC):
|
|
78
|
+
"""Change capture for an observed send. It never manages a transaction."""
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
@abstractmethod
|
|
82
|
+
def changes(self) -> list[PreviewChange]:
|
|
83
|
+
"""Captured changes."""
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def changes_truncated(self) -> bool:
|
|
87
|
+
"""Whether changes were omitted because of a capture limit."""
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
@abstractmethod
|
|
91
|
+
def close(self) -> None:
|
|
92
|
+
"""Stop observing."""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class PreviewProvider(ABC):
|
|
96
|
+
"""Opens a rollback-only scope for the selected API operation."""
|
|
97
|
+
|
|
98
|
+
#: Public database label, never a connection string.
|
|
99
|
+
database: str | None = None
|
|
100
|
+
#: SQL provider id for the workbench's store mark: ``sqlite``, ``postgresql``, ``mysql``, ``mariadb``...
|
|
101
|
+
system: str | None = None
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def is_available(self) -> bool:
|
|
105
|
+
"""Whether the provider currently supports rollback previews."""
|
|
106
|
+
return True
|
|
107
|
+
|
|
108
|
+
@abstractmethod
|
|
109
|
+
def begin(self, scope: RequestScope) -> PreviewSession:
|
|
110
|
+
"""Start a rollback scope bound to ``scope``. Clean up after yourself if it fails."""
|
|
111
|
+
|
|
112
|
+
def begin_observation(self, scope: RequestScope) -> PreviewObservation | None:
|
|
113
|
+
"""Optionally observe changes without a transaction."""
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
async def run_in_thread(function: Callable[..., T], *args: Any) -> T:
|
|
118
|
+
"""Run a blocking callable in the default executor, preserving context variables."""
|
|
119
|
+
context = contextvars.copy_context()
|
|
120
|
+
loop = asyncio.get_running_loop()
|
|
121
|
+
return await loop.run_in_executor(None, functools.partial(context.run, function, *args))
|
sendproof_core/py.typed
ADDED
|
File without changes
|