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.
Files changed (209) hide show
  1. sendproof_core/__init__.py +56 -0
  2. sendproof_core/assets.py +71 -0
  3. sendproof_core/capture.py +416 -0
  4. sendproof_core/effects.py +79 -0
  5. sendproof_core/identity.py +22 -0
  6. sendproof_core/jsonsafe.py +103 -0
  7. sendproof_core/limits.py +24 -0
  8. sendproof_core/marker.py +131 -0
  9. sendproof_core/options.py +129 -0
  10. sendproof_core/protocol.py +132 -0
  11. sendproof_core/provider.py +121 -0
  12. sendproof_core/py.typed +0 -0
  13. sendproof_core/redaction.py +88 -0
  14. sendproof_core/scope.py +146 -0
  15. sendproof_core/stores/__init__.py +119 -0
  16. sendproof_core/stores/base.py +99 -0
  17. sendproof_core/stores/cassandra_hook.py +173 -0
  18. sendproof_core/stores/classify.py +153 -0
  19. sendproof_core/stores/classify_batch_two.py +397 -0
  20. sendproof_core/stores/cosmos_hook.py +214 -0
  21. sendproof_core/stores/dynamodb_hook.py +214 -0
  22. sendproof_core/stores/elasticsearch_hook.py +248 -0
  23. sendproof_core/stores/firestore_hook.py +459 -0
  24. sendproof_core/stores/guard.py +205 -0
  25. sendproof_core/stores/mongo_hook.py +1406 -0
  26. sendproof_core/stores/redis_hook.py +536 -0
  27. sendproof_core/stores/tables.py +1486 -0
  28. sendproof_core/stores/versions.py +46 -0
  29. sendproof_core/sync_engine.py +308 -0
  30. sendproof_core/trace_store.py +92 -0
  31. sendproof_core/txguard.py +237 -0
  32. sendproof_core/ui/action-bar.js +91 -0
  33. sendproof_core/ui/api.js +239 -0
  34. sendproof_core/ui/app.css +848 -0
  35. sendproof_core/ui/app.js +742 -0
  36. sendproof_core/ui/autofill.js +137 -0
  37. sendproof_core/ui/code-copy.js +71 -0
  38. sendproof_core/ui/code-picker.js +149 -0
  39. sendproof_core/ui/commands.js +197 -0
  40. sendproof_core/ui/components.js +77 -0
  41. sendproof_core/ui/context-bar.js +82 -0
  42. sendproof_core/ui/copy.js +92 -0
  43. sendproof_core/ui/coverage-popover.js +35 -0
  44. sendproof_core/ui/crumb-fit.js +80 -0
  45. sendproof_core/ui/deprecation.js +164 -0
  46. sendproof_core/ui/display-settings.js +175 -0
  47. sendproof_core/ui/doc-diff.js +209 -0
  48. sendproof_core/ui/docs-view.js +347 -0
  49. sendproof_core/ui/favicon.png +0 -0
  50. sendproof_core/ui/favicon.svg +1 -0
  51. sendproof_core/ui/field-help.js +52 -0
  52. sendproof_core/ui/field-modules.js +23 -0
  53. sendproof_core/ui/fields/controls.js +179 -0
  54. sendproof_core/ui/fields/dom.js +36 -0
  55. sendproof_core/ui/fields/infer.js +71 -0
  56. sendproof_core/ui/fields/lookup-source.js +63 -0
  57. sendproof_core/ui/fields/lookup.js +285 -0
  58. sendproof_core/ui/fields/render.js +496 -0
  59. sendproof_core/ui/fields/select.js +175 -0
  60. sendproof_core/ui/fields/validate.js +363 -0
  61. sendproof_core/ui/fields/validation-formats.js +164 -0
  62. sendproof_core/ui/fields/validation-references.js +68 -0
  63. sendproof_core/ui/fields/validation-values.js +137 -0
  64. sendproof_core/ui/generate-menu.js +44 -0
  65. sendproof_core/ui/generate.js +184 -0
  66. sendproof_core/ui/header-editor.js +777 -0
  67. sendproof_core/ui/headers.js +188 -0
  68. sendproof_core/ui/highlight.js +257 -0
  69. sendproof_core/ui/history-popover.js +24 -0
  70. sendproof_core/ui/i18n.js +253 -0
  71. sendproof_core/ui/icons.js +87 -0
  72. sendproof_core/ui/index.html +70 -0
  73. sendproof_core/ui/issues.js +187 -0
  74. sendproof_core/ui/json-view.js +166 -0
  75. sendproof_core/ui/lang-icons.js +62 -0
  76. sendproof_core/ui/layout.js +262 -0
  77. sendproof_core/ui/listbox.js +334 -0
  78. sendproof_core/ui/locales/ar-capture.js +366 -0
  79. sendproof_core/ui/locales/ar-stores.js +116 -0
  80. sendproof_core/ui/locales/ar.js +561 -0
  81. sendproof_core/ui/locales/cs-capture.js +442 -0
  82. sendproof_core/ui/locales/cs-stores.js +116 -0
  83. sendproof_core/ui/locales/cs.js +689 -0
  84. sendproof_core/ui/locales/da-capture.js +347 -0
  85. sendproof_core/ui/locales/da-stores.js +116 -0
  86. sendproof_core/ui/locales/da.js +522 -0
  87. sendproof_core/ui/locales/de-capture.js +347 -0
  88. sendproof_core/ui/locales/de-stores.js +116 -0
  89. sendproof_core/ui/locales/de.js +519 -0
  90. sendproof_core/ui/locales/el-capture.js +347 -0
  91. sendproof_core/ui/locales/el-stores.js +116 -0
  92. sendproof_core/ui/locales/el.js +520 -0
  93. sendproof_core/ui/locales/en-capture.js +349 -0
  94. sendproof_core/ui/locales/en-stores.js +95 -0
  95. sendproof_core/ui/locales/en.js +522 -0
  96. sendproof_core/ui/locales/es-capture.js +353 -0
  97. sendproof_core/ui/locales/es-stores.js +116 -0
  98. sendproof_core/ui/locales/es.js +525 -0
  99. sendproof_core/ui/locales/fa-capture.js +348 -0
  100. sendproof_core/ui/locales/fa-stores.js +116 -0
  101. sendproof_core/ui/locales/fa.js +521 -0
  102. sendproof_core/ui/locales/fi-capture.js +347 -0
  103. sendproof_core/ui/locales/fi-stores.js +116 -0
  104. sendproof_core/ui/locales/fi.js +523 -0
  105. sendproof_core/ui/locales/fr-capture.js +353 -0
  106. sendproof_core/ui/locales/fr-stores.js +116 -0
  107. sendproof_core/ui/locales/fr.js +525 -0
  108. sendproof_core/ui/locales/he-capture.js +358 -0
  109. sendproof_core/ui/locales/he-stores.js +116 -0
  110. sendproof_core/ui/locales/he.js +529 -0
  111. sendproof_core/ui/locales/hi-capture.js +348 -0
  112. sendproof_core/ui/locales/hi-stores.js +116 -0
  113. sendproof_core/ui/locales/hi.js +523 -0
  114. sendproof_core/ui/locales/id-capture.js +347 -0
  115. sendproof_core/ui/locales/id-stores.js +116 -0
  116. sendproof_core/ui/locales/id.js +521 -0
  117. sendproof_core/ui/locales/it-capture.js +361 -0
  118. sendproof_core/ui/locales/it-stores.js +116 -0
  119. sendproof_core/ui/locales/it.js +523 -0
  120. sendproof_core/ui/locales/ja-capture.js +346 -0
  121. sendproof_core/ui/locales/ja-stores.js +116 -0
  122. sendproof_core/ui/locales/ja.js +521 -0
  123. sendproof_core/ui/locales/ko-capture.js +346 -0
  124. sendproof_core/ui/locales/ko-stores.js +116 -0
  125. sendproof_core/ui/locales/ko.js +522 -0
  126. sendproof_core/ui/locales/nb-capture.js +349 -0
  127. sendproof_core/ui/locales/nb-stores.js +116 -0
  128. sendproof_core/ui/locales/nb.js +521 -0
  129. sendproof_core/ui/locales/nl-capture.js +355 -0
  130. sendproof_core/ui/locales/nl-stores.js +116 -0
  131. sendproof_core/ui/locales/nl.js +520 -0
  132. sendproof_core/ui/locales/pl-capture.js +432 -0
  133. sendproof_core/ui/locales/pl-stores.js +116 -0
  134. sendproof_core/ui/locales/pl.js +528 -0
  135. sendproof_core/ui/locales/pt-BR-capture.js +350 -0
  136. sendproof_core/ui/locales/pt-BR-stores.js +116 -0
  137. sendproof_core/ui/locales/pt-BR.js +523 -0
  138. sendproof_core/ui/locales/pt-PT-capture.js +350 -0
  139. sendproof_core/ui/locales/pt-PT-stores.js +116 -0
  140. sendproof_core/ui/locales/pt-PT.js +523 -0
  141. sendproof_core/ui/locales/ru-capture.js +437 -0
  142. sendproof_core/ui/locales/ru-stores.js +116 -0
  143. sendproof_core/ui/locales/ru.js +624 -0
  144. sendproof_core/ui/locales/sv-capture.js +349 -0
  145. sendproof_core/ui/locales/sv-stores.js +116 -0
  146. sendproof_core/ui/locales/sv.js +518 -0
  147. sendproof_core/ui/locales/th-capture.js +347 -0
  148. sendproof_core/ui/locales/th-stores.js +116 -0
  149. sendproof_core/ui/locales/th.js +521 -0
  150. sendproof_core/ui/locales/tr-capture.js +348 -0
  151. sendproof_core/ui/locales/tr-stores.js +116 -0
  152. sendproof_core/ui/locales/tr.js +521 -0
  153. sendproof_core/ui/locales/uk-capture.js +442 -0
  154. sendproof_core/ui/locales/uk-stores.js +116 -0
  155. sendproof_core/ui/locales/uk.js +630 -0
  156. sendproof_core/ui/locales/vi-capture.js +346 -0
  157. sendproof_core/ui/locales/vi-stores.js +116 -0
  158. sendproof_core/ui/locales/vi.js +523 -0
  159. sendproof_core/ui/locales/zh-Hans-capture.js +347 -0
  160. sendproof_core/ui/locales/zh-Hans-stores.js +116 -0
  161. sendproof_core/ui/locales/zh-Hans.js +523 -0
  162. sendproof_core/ui/locales/zh-Hant-capture.js +346 -0
  163. sendproof_core/ui/locales/zh-Hant-stores.js +116 -0
  164. sendproof_core/ui/locales/zh-Hant.js +522 -0
  165. sendproof_core/ui/manifest.json +866 -0
  166. sendproof_core/ui/markdown.js +39 -0
  167. sendproof_core/ui/model-view.js +182 -0
  168. sendproof_core/ui/navigation.js +233 -0
  169. sendproof_core/ui/operation-header.js +76 -0
  170. sendproof_core/ui/operations.js +7 -0
  171. sendproof_core/ui/overview-view.js +63 -0
  172. sendproof_core/ui/personas.js +59 -0
  173. sendproof_core/ui/popover.js +71 -0
  174. sendproof_core/ui/preview-false.js +108 -0
  175. sendproof_core/ui/request-editor.js +496 -0
  176. sendproof_core/ui/response-metadata.js +354 -0
  177. sendproof_core/ui/response-viewer.js +618 -0
  178. sendproof_core/ui/result-blocked.js +155 -0
  179. sendproof_core/ui/result-capture.js +25 -0
  180. sendproof_core/ui/result-database.js +185 -0
  181. sendproof_core/ui/result-effects.js +176 -0
  182. sendproof_core/ui/result-headers.js +106 -0
  183. sendproof_core/ui/result-logs.js +408 -0
  184. sendproof_core/ui/result-states.js +213 -0
  185. sendproof_core/ui/results.js +371 -0
  186. sendproof_core/ui/router.js +118 -0
  187. sendproof_core/ui/schema-model.js +336 -0
  188. sendproof_core/ui/schema-tree.js +344 -0
  189. sendproof_core/ui/schema.js +397 -0
  190. sendproof_core/ui/security.js +31 -0
  191. sendproof_core/ui/seeded-menu.js +69 -0
  192. sendproof_core/ui/settings.js +93 -0
  193. sendproof_core/ui/shortcuts-sheet.js +73 -0
  194. sendproof_core/ui/shortcuts.js +190 -0
  195. sendproof_core/ui/sidebar.js +289 -0
  196. sendproof_core/ui/signin.js +259 -0
  197. sendproof_core/ui/snippets.js +530 -0
  198. sendproof_core/ui/store-marks.js +47 -0
  199. sendproof_core/ui/stores.js +131 -0
  200. sendproof_core/ui/styles.css +971 -0
  201. sendproof_core/ui/toggletip.js +53 -0
  202. sendproof_core/ui/uuid.js +10 -0
  203. sendproof_core/ui/view.js +122 -0
  204. sendproof_core/ui/views.css +653 -0
  205. sendproof_core/workbench.py +310 -0
  206. sendproof_core-0.1.0a1.dist-info/METADATA +116 -0
  207. sendproof_core-0.1.0a1.dist-info/RECORD +209 -0
  208. sendproof_core-0.1.0a1.dist-info/WHEEL +4 -0
  209. sendproof_core-0.1.0a1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,536 @@
1
+ """Sendproof write guard for Redis (``spec/data-stores.md``, ``guard`` mode).
2
+
3
+ ``redis_store(client)`` hooks a redis-py client (``redis.Redis`` or ``redis.asyncio.Redis``) or its
4
+ connection pool in place. The hook is a ``Connection`` subclass: every command, whether sent alone
5
+ or queued in a pipeline or ``MULTI``, is classified **before any byte of it is packed or written**:
6
+
7
+ * ``send_command``, ``pack_command`` and ``pack_commands`` are overridden, so single commands,
8
+ scripts and raw ``execute_command`` calls are covered, and so is every pipeline. A pipeline or
9
+ transaction is classified as a whole before its first command is sent, so a refused write sends
10
+ nothing, not even ``MULTI``.
11
+ * Reads run normally. In a Preview the first write raises
12
+ :class:`~sendproof_core.stores.guard.PreviewWriteBlocked` and the Preview answers 409. Session
13
+ commands (``AUTH``, ``HELLO``, ``SELECT``, ``PING``...) are never guarded or logged, so the
14
+ password never reaches a capture.
15
+ * Every other command becomes a ``Db`` log entry whose statement keeps the command name and key
16
+ arguments only (``SET session:42 ?``).
17
+
18
+ The same hook works for a client you build yourself, through the connection class::
19
+
20
+ store = redis_store(name="cache")
21
+ pool = redis.ConnectionPool.from_url(url, connection_class=store.connection_class)
22
+
23
+ and for django-redis or Django's ``RedisCache`` through their ``connection_class`` option.
24
+
25
+ Coverage: only hooked clients are covered. A client built from an unhooked pool, a Redis Cluster
26
+ or Sentinel client built without the connection class, or a raw socket is not.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import inspect
32
+ import re
33
+ import time
34
+ from collections import deque
35
+ from typing import Any, Iterable, Optional
36
+
37
+ from ..scope import current_scope
38
+ from .base import DataStore
39
+ from .classify import SESSION, TRANSACTION, WRITE, classify_redis
40
+ from .guard import PreviewWriteBlocked, guard, read_set, refuse_unattributed, store_label
41
+
42
+ # Commands whose every argument is a key.
43
+ _ALL_KEYS = frozenset({
44
+ "DEL", "UNLINK", "EXISTS", "TOUCH", "MGET", "SUNION", "SINTER", "SDIFF", "WATCH", "PFCOUNT", "PFMERGE",
45
+ "SUNIONSTORE", "SINTERSTORE", "SDIFFSTORE", "RENAME", "RENAMENX", "RPOPLPUSH", "COPY", "LMOVE", "BLMOVE",
46
+ "SMOVE", "JSON.MGET", "TS.MGET",
47
+ })
48
+ # Commands whose arguments alternate key, value.
49
+ _PAIRS = frozenset({"MSET", "MSETNX"})
50
+ # Commands that name their keys after a key count: EVAL script numkeys key... arg...
51
+ _NUMKEYS = frozenset({"EVAL", "EVALSHA", "EVAL_RO", "EVALSHA_RO", "FCALL", "FCALL_RO"})
52
+ # Container commands that put the key after the subcommand: OBJECT ENCODING key.
53
+ _KEY_AT_ONE = frozenset({"OBJECT", "MEMORY", "XINFO", "XGROUP"})
54
+ # Container commands: their first argument is a fixed subcommand word, not data, so it is shown.
55
+ _CONTAINERS = frozenset({
56
+ "CONFIG", "CLIENT", "OBJECT", "MEMORY", "XINFO", "XGROUP", "SCRIPT", "FUNCTION", "ACL", "CLUSTER", "COMMAND",
57
+ "PUBSUB", "LATENCY", "MODULE", "SLOWLOG", "DEBUG",
58
+ })
59
+ # Commands with no key. Their arguments (patterns, scripts, options) are all shown as ``?``.
60
+ _NO_KEYS = frozenset({
61
+ "DBSIZE", "KEYS", "SCAN", "RANDOMKEY", "LOLWUT", "SCRIPT", "CONFIG", "CLIENT", "FLUSHALL", "FLUSHDB", "SAVE",
62
+ "BGSAVE", "BGREWRITEAOF", "SHUTDOWN", "SLAVEOF", "REPLICAOF", "ACL", "MODULE", "DEBUG", "MONITOR", "PUBSUB",
63
+ "FUNCTION", "CLUSTER", "FAILOVER", "SWAPDB", "MOVE", "SENTINEL", "LATENCY", "SLOWLOG", "WAIT", "FT._LIST",
64
+ "BITOP", "ZUNIONSTORE", "ZINTERSTORE", "ZDIFFSTORE", "ZUNION", "ZINTER", "ZDIFF", "SINTERCARD", "PUBLISH",
65
+ "SPUBLISH", "SUBSCRIBE", "PSUBSCRIBE", "SSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "SUNSUBSCRIBE", "PING", "ECHO",
66
+ })
67
+
68
+
69
+ def _text(value: Any) -> str:
70
+ if isinstance(value, (bytes, bytearray, memoryview)):
71
+ return bytes(value).decode("utf-8", errors="replace")
72
+ return str(value)
73
+
74
+
75
+ def _key_indexes(name: str, args: list[Any]) -> list[int]:
76
+ """Positions of the key arguments of a command, as far as the table below knows them.
77
+
78
+ A command the table does not know shows no keys: its arguments might be values, and a value
79
+ never appears in a ``Db`` entry.
80
+ """
81
+ if name in _NO_KEYS:
82
+ if name in ("BITOP", "ZUNIONSTORE", "ZINTERSTORE", "ZDIFFSTORE", "ZUNION", "ZINTER", "ZDIFF", "SINTERCARD"):
83
+ return _counted_keys(name, args)
84
+ return []
85
+ if name in _ALL_KEYS:
86
+ return list(range(len(args)))
87
+ if name in _PAIRS:
88
+ return list(range(0, len(args), 2))
89
+ if name in _NUMKEYS:
90
+ try:
91
+ count = int(_text(args[1]))
92
+ except (IndexError, ValueError):
93
+ return []
94
+ return list(range(2, min(len(args), 2 + count)))
95
+ if name in _KEY_AT_ONE:
96
+ return [1] if len(args) > 1 else []
97
+ return [0] if args else []
98
+
99
+
100
+ def _counted_keys(name: str, args: list[Any]) -> list[int]:
101
+ """Keys of ``BITOP op dest key...``, ``ZUNIONSTORE dest n key...`` and ``ZUNION n key...``."""
102
+ try:
103
+ if name == "BITOP":
104
+ return list(range(1, len(args)))
105
+ if name in ("ZUNIONSTORE", "ZINTERSTORE", "ZDIFFSTORE"):
106
+ return [0, *range(2, min(len(args), 2 + int(_text(args[1]))))]
107
+ return list(range(1, min(len(args), 1 + int(_text(args[0]))))) # ZUNION n key..., SINTERCARD n key...
108
+ except (IndexError, ValueError):
109
+ return []
110
+
111
+
112
+ def describe_command(name: str, args: list[Any]) -> tuple[str, Optional[str]]:
113
+ """The ``Db`` statement and target of a command: the name, then each key argument as written and
114
+ every other argument as ``?`` (``SET session:42 ?``). Values never appear.
115
+ """
116
+ keys = set(_key_indexes(name, args))
117
+ shown = [_text(arg) if index in keys else "?" for index, arg in enumerate(args)]
118
+ if name in _CONTAINERS and args and re.fullmatch(r"[A-Za-z_-]{1,32}", _text(args[0])):
119
+ shown[0] = _text(args[0]).upper()
120
+ target = _text(args[min(keys)]) if keys else None
121
+ return " ".join([name, *shown]), target
122
+
123
+
124
+ def _split(command: Iterable[Any]) -> tuple[str, list[Any]]:
125
+ """The upper-case command name (its first word) and its arguments, as redis-py passes them."""
126
+ items = list(command)
127
+ if not items:
128
+ return "", []
129
+ words = _text(items[0]).split(" ")
130
+ return words[0].upper(), [*words[1:], *items[1:]]
131
+
132
+
133
+ class _Settings:
134
+ """Per-store settings every guarded connection of that store shares."""
135
+
136
+ def __init__(self, reads: Optional[frozenset[str]]) -> None:
137
+ self.reads = reads
138
+
139
+
140
+ #: Commands after which a connection receives messages it never asked for, so replies no longer
141
+ #: pair one-to-one with commands: such a connection logs its commands untimed, as they are sent.
142
+ _PUSH_MODE = frozenset({"SUBSCRIBE", "PSUBSCRIBE", "SSUBSCRIBE", "MONITOR"})
143
+
144
+ #: One command waiting for its reply: the capture to log it in, then the ``Db`` entry's fields.
145
+ _Entry = tuple # (capture, name, target, namespace, statement)
146
+
147
+
148
+ def _error_code(error: BaseException) -> str:
149
+ """The Redis error code of a refused command (``WRONGTYPE``, ``ERR``), or the error's class name.
150
+
151
+ Only the code is kept: the rest of an error message may quote a key or a value.
152
+ """
153
+ from redis.exceptions import ResponseError
154
+
155
+ if type(error) is ResponseError:
156
+ word = str(error).split(" ", 1)[0]
157
+ return word if re.fullmatch(r"[A-Z][A-Z_]{1,31}", word) else "ERR"
158
+ return type(error).__name__
159
+
160
+
161
+ class _GuardBase:
162
+ """What the synchronous and asynchronous guarded connections share: classify, guard, log.
163
+
164
+ Logging pairs replies with commands. redis-py reads exactly one reply for each command it sends
165
+ (pipelines and ``MULTI`` included), so each sent command waits in a queue on its connection and
166
+ its ``Db`` entry is written when its reply arrives, with the time it took and the Redis error
167
+ code if it failed. A connection in pub/sub or ``MONITOR`` mode receives replies nobody asked
168
+ for, so from then on it logs each command as it is sent, without timing.
169
+ """
170
+
171
+ _sendproof_settings: _Settings = _Settings(None)
172
+ _sendproof_handshake = 0
173
+ _sendproof_skip = False
174
+ _sendproof_in_multi = False
175
+ _sendproof_dirty = False
176
+ _sendproof_untimed = False
177
+ _sendproof_staged: Optional[list[Optional[_Entry]]] = None
178
+ _sendproof_waiting: Optional[deque] = None
179
+
180
+ def _sendproof_kind(self, command: Iterable[Any]) -> tuple[str, str, list[Any], str]:
181
+ items = list(command)
182
+ name, args = _split(items)
183
+ full = _text(items[0]).upper() if items else ""
184
+ return classify_redis(full, items[1:], self._sendproof_settings.reads), name, args, full
185
+
186
+ def _sendproof_namespace(self) -> Optional[str]:
187
+ database = getattr(self, "db", None)
188
+ return None if database is None else str(database)
189
+
190
+ def _sendproof_check(self, commands: list[Iterable[Any]], single: bool) -> None:
191
+ """Classify ``commands`` as one batch and refuse the first write, then stage their log entries
192
+ for :meth:`_sendproof_sent`."""
193
+ if not commands:
194
+ return
195
+ if self._sendproof_handshake:
196
+ # A pub/sub client re-subscribes while it reconnects: its replies stop pairing from here.
197
+ if any(_split(command)[0] in _PUSH_MODE for command in commands):
198
+ self._sendproof_untimed, self._sendproof_waiting = True, None
199
+ return
200
+ classified = [self._sendproof_kind(command) for command in commands]
201
+ scope = current_scope()
202
+ try:
203
+ for kind, name, _args, _full in classified:
204
+ guard("redis", name, kind)
205
+ if scope is None and any(kind == WRITE for kind, *_ in classified):
206
+ refuse_unattributed("redis", next(name for kind, name, *_ in classified if kind == WRITE))
207
+ except PreviewWriteBlocked:
208
+ if self._sendproof_in_multi:
209
+ self._sendproof_abandon()
210
+ raise
211
+ if single:
212
+ kind, name, _args, _full = classified[0]
213
+ if kind == TRANSACTION:
214
+ self._sendproof_in_multi = name == "MULTI" or (self._sendproof_in_multi and name not in ("EXEC", "DISCARD"))
215
+ staged: list[Optional[_Entry]] = []
216
+ for kind, name, args, _full in classified:
217
+ if scope is None or kind in (SESSION, TRANSACTION):
218
+ staged.append(None) # still holds the reply's place in the queue
219
+ continue
220
+ statement, target = describe_command(name, args)
221
+ staged.append((scope.capture, name, target, self._sendproof_namespace(), statement))
222
+ if any(name in _PUSH_MODE for _kind, name, _args, _full in classified):
223
+ self._sendproof_untimed = True
224
+ self._sendproof_waiting = None
225
+ # Each packed batch is sent by exactly one send_packed_command, so the latest batch replaces
226
+ # any that was packed and never sent.
227
+ self._sendproof_staged = staged
228
+
229
+ # -- pairing replies with commands
230
+ def _sendproof_take(self) -> Optional[list[Optional[_Entry]]]:
231
+ """The entries of the batch about to be sent. Taken before sending, so a health-check ``PING``
232
+ the driver sends first stages and pairs its own entry."""
233
+ staged, self._sendproof_staged = self._sendproof_staged, None
234
+ return staged
235
+
236
+ def _sendproof_sent(self, staged: Optional[list[Optional[_Entry]]], error: Optional[BaseException]) -> None:
237
+ """Queue a sent batch for its replies, or log it now when it failed to send or replies can't be paired."""
238
+ if not staged:
239
+ return
240
+ if error is not None or self._sendproof_untimed:
241
+ for entry in staged:
242
+ self._sendproof_log(entry, None, None if error is None else type(error).__name__)
243
+ return
244
+ now = time.perf_counter()
245
+ waiting = self._sendproof_waiting
246
+ if waiting is None:
247
+ waiting = self._sendproof_waiting = deque()
248
+ waiting.extend((entry, now) for entry in staged)
249
+
250
+ def _sendproof_replied(self, error: Optional[BaseException]) -> None:
251
+ """Log the oldest command waiting on this connection, now that its reply (or error) arrived."""
252
+ waiting = self._sendproof_waiting
253
+ if not waiting:
254
+ return
255
+ entry, sent = waiting.popleft()
256
+ self._sendproof_log(entry, (time.perf_counter() - sent) * 1000, None if error is None else _error_code(error))
257
+ if error is not None and not _is_reply_error(error):
258
+ self._sendproof_flush(error) # the connection failed: no other reply is coming
259
+
260
+ def _sendproof_flush(self, error: Optional[BaseException]) -> None:
261
+ """Log every command still waiting, with the error that ended the connection.
262
+
263
+ Called when the connection closes, which also ends pub/sub mode: a pooled connection a
264
+ ``PubSub`` released pairs replies again on its next use.
265
+ """
266
+ self._sendproof_untimed = False
267
+ waiting, self._sendproof_waiting = self._sendproof_waiting, None
268
+ for entry, _sent in waiting or ():
269
+ self._sendproof_log(entry, None, type(error).__name__ if error is not None else "ConnectionError")
270
+
271
+ def _sendproof_pairs(self, kwargs: dict) -> bool:
272
+ """Whether this read answers a command: not during the handshake, and not a push-message read."""
273
+ return not self._sendproof_handshake and not kwargs.get("push_request")
274
+
275
+ @staticmethod
276
+ def _sendproof_log(entry: Optional[_Entry], elapsed_ms: Optional[float], error: Optional[str]) -> None:
277
+ if entry is None:
278
+ return
279
+ capture, name, target, namespace, statement = entry
280
+ capture.record_db("redis", name, target=target, namespace=namespace, statement=statement,
281
+ elapsed_ms=elapsed_ms, error=error)
282
+
283
+ def _sendproof_abandon(self) -> None: # pragma: no cover - overridden
284
+ raise NotImplementedError
285
+
286
+
287
+ def _is_reply_error(error: BaseException) -> bool:
288
+ """A refusal Redis sent as its reply, after which the connection is still in step."""
289
+ from redis.exceptions import ResponseError
290
+
291
+ return isinstance(error, ResponseError)
292
+
293
+
294
+ class _SyncGuard(_GuardBase):
295
+ """Mixin for ``redis.Connection`` and its subclasses."""
296
+
297
+ def send_command(self, *args: Any, **kwargs: Any) -> Any:
298
+ if self._sendproof_skip:
299
+ return super().send_command(*args, **kwargs) # type: ignore[misc]
300
+ self._sendproof_check([args], single=True)
301
+ self._sendproof_skip = True
302
+ try:
303
+ return super().send_command(*args, **kwargs) # type: ignore[misc]
304
+ finally:
305
+ self._sendproof_skip = False
306
+
307
+ def pack_command(self, *args: Any) -> Any:
308
+ if not self._sendproof_skip:
309
+ self._sendproof_check([args], single=True)
310
+ return super().pack_command(*args) # type: ignore[misc]
311
+
312
+ def pack_commands(self, commands: Iterable[Iterable[Any]]) -> Any:
313
+ batch = [tuple(command) for command in commands]
314
+ if not self._sendproof_skip:
315
+ self._sendproof_check(batch, single=False)
316
+ self._sendproof_skip = True
317
+ try:
318
+ return super().pack_commands(batch) # type: ignore[misc]
319
+ finally:
320
+ self._sendproof_skip = False
321
+
322
+ def on_connect(self) -> Any:
323
+ # Handshake commands (HELLO, AUTH, CLIENT SETINFO, SELECT...) set up the session and never
324
+ # touch data, so they are not classified, and never reach a capture.
325
+ self._sendproof_handshake += 1
326
+ try:
327
+ return super().on_connect() # type: ignore[misc]
328
+ finally:
329
+ self._sendproof_handshake -= 1
330
+
331
+ def on_connect_check_health(self, *args: Any, **kwargs: Any) -> Any:
332
+ self._sendproof_handshake += 1
333
+ try:
334
+ return super().on_connect_check_health(*args, **kwargs) # type: ignore[misc]
335
+ finally:
336
+ self._sendproof_handshake -= 1
337
+
338
+ def send_packed_command(self, command: Any, check_health: bool = True) -> Any:
339
+ staged = self._sendproof_take()
340
+ try:
341
+ result = super().send_packed_command(command, check_health) # type: ignore[misc]
342
+ except BaseException as error:
343
+ self._sendproof_sent(staged, error)
344
+ raise
345
+ self._sendproof_sent(staged, None)
346
+ return result
347
+
348
+ def read_response(self, *args: Any, **kwargs: Any) -> Any:
349
+ if not self._sendproof_pairs(kwargs):
350
+ return super().read_response(*args, **kwargs) # type: ignore[misc]
351
+ try:
352
+ response = super().read_response(*args, **kwargs) # type: ignore[misc]
353
+ except Exception as error:
354
+ self._sendproof_replied(error)
355
+ raise
356
+ self._sendproof_replied(None)
357
+ return response
358
+
359
+ def disconnect(self, *args: Any, **kwargs: Any) -> Any:
360
+ self._sendproof_flush(None)
361
+ return super().disconnect(*args, **kwargs) # type: ignore[misc]
362
+
363
+ def _sendproof_abandon(self) -> None:
364
+ """Close the socket: a write refused after ``MULTI`` must not be followed by an ``EXEC``."""
365
+ self._sendproof_in_multi = False
366
+ try:
367
+ self.disconnect() # type: ignore[attr-defined]
368
+ except Exception:
369
+ pass
370
+
371
+
372
+ class _AsyncGuard(_GuardBase):
373
+ """Mixin for ``redis.asyncio.Connection`` and its subclasses."""
374
+
375
+ def pack_command(self, *args: Any) -> Any:
376
+ if not self._sendproof_skip:
377
+ self._sendproof_check([args], single=True)
378
+ return super().pack_command(*args) # type: ignore[misc]
379
+
380
+ def pack_commands(self, commands: Iterable[Iterable[Any]]) -> Any:
381
+ batch = [tuple(command) for command in commands]
382
+ if not self._sendproof_skip:
383
+ self._sendproof_check(batch, single=False)
384
+ self._sendproof_skip = True
385
+ try:
386
+ return super().pack_commands(batch) # type: ignore[misc]
387
+ finally:
388
+ self._sendproof_skip = False
389
+
390
+ async def on_connect(self) -> Any:
391
+ self._sendproof_handshake += 1
392
+ try:
393
+ return await super().on_connect() # type: ignore[misc]
394
+ finally:
395
+ self._sendproof_handshake -= 1
396
+
397
+ async def on_connect_check_health(self, *args: Any, **kwargs: Any) -> Any:
398
+ self._sendproof_handshake += 1
399
+ try:
400
+ return await super().on_connect_check_health(*args, **kwargs) # type: ignore[misc]
401
+ finally:
402
+ self._sendproof_handshake -= 1
403
+
404
+ async def send_packed_command(self, command: Any, check_health: bool = True) -> Any:
405
+ staged = self._sendproof_take()
406
+ if self._sendproof_dirty:
407
+ self._sendproof_dirty = False
408
+ await self.disconnect() # type: ignore[attr-defined]
409
+ try:
410
+ result = await super().send_packed_command(command, check_health) # type: ignore[misc]
411
+ except BaseException as error:
412
+ self._sendproof_sent(staged, error)
413
+ raise
414
+ self._sendproof_sent(staged, None)
415
+ return result
416
+
417
+ async def read_response(self, *args: Any, **kwargs: Any) -> Any:
418
+ if not self._sendproof_pairs(kwargs):
419
+ return await super().read_response(*args, **kwargs) # type: ignore[misc]
420
+ try:
421
+ response = await super().read_response(*args, **kwargs) # type: ignore[misc]
422
+ except Exception as error:
423
+ self._sendproof_replied(error)
424
+ raise
425
+ self._sendproof_replied(None)
426
+ return response
427
+
428
+ async def disconnect(self, *args: Any, **kwargs: Any) -> Any:
429
+ self._sendproof_flush(None)
430
+ return await super().disconnect(*args, **kwargs) # type: ignore[misc]
431
+
432
+ def _sendproof_abandon(self) -> None:
433
+ """Close the socket before the next send: a write refused after ``MULTI`` must not be followed by an ``EXEC``."""
434
+ self._sendproof_in_multi = False
435
+ self._sendproof_dirty = True
436
+
437
+
438
+ _classes: dict[tuple[type, int], type] = {}
439
+
440
+
441
+ def _is_async(connection_class: type) -> bool:
442
+ """Whether a redis-py connection class is an ``asyncio`` one."""
443
+ return inspect.iscoroutinefunction(getattr(connection_class, "connect", None))
444
+
445
+
446
+ def guarded_connection_class(base: type, settings: _Settings) -> type:
447
+ """A subclass of the redis-py connection class ``base`` that classifies every command before sending it."""
448
+ key = (base, id(settings))
449
+ found = _classes.get(key)
450
+ if found is None:
451
+ mixin = _AsyncGuard if _is_async(base) else _SyncGuard
452
+ found = _classes[key] = type(f"Guarded{base.__name__}", (mixin, base), {
453
+ "_sendproof_settings": settings, "__module__": __name__,
454
+ })
455
+ return found
456
+
457
+
458
+ def _pool_connections(pool: Any) -> list[Any]:
459
+ """Every connection a redis-py pool currently holds, free or in use."""
460
+ found: list[Any] = []
461
+ for attribute in ("_available_connections", "_in_use_connections", "_connections"):
462
+ found.extend(c for c in list(getattr(pool, attribute, None) or ()) if c is not None)
463
+ return found
464
+
465
+
466
+ def _hook_pool(pool: Any, settings: _Settings) -> None:
467
+ """Guard a connection pool: its future connections, and the ones it already holds."""
468
+ if getattr(pool.connection_class, "_sendproof_settings", None) is not None and issubclass(
469
+ pool.connection_class, (_SyncGuard, _AsyncGuard)
470
+ ):
471
+ raise TypeError("This Redis client is already hooked by redis_store.")
472
+ original = pool.connection_class
473
+ pool.connection_class = guarded_connection_class(original, settings)
474
+ for connection in _pool_connections(pool):
475
+ if not isinstance(connection, (_SyncGuard, _AsyncGuard)):
476
+ try:
477
+ connection.__class__ = guarded_connection_class(type(connection), settings)
478
+ except TypeError: # a class with a incompatible layout: new connections are still guarded
479
+ pass
480
+
481
+
482
+ class RedisStore(DataStore):
483
+ """A hooked Redis client, ready for ``data_stores``."""
484
+
485
+ system = "redis"
486
+
487
+ def __init__(self, name: Optional[str], settings: _Settings) -> None:
488
+ self.name = name
489
+ self._settings = settings
490
+ #: A guarded ``redis.Connection`` for pools you build yourself.
491
+ self.connection_class = guarded_connection_class(_default_connection(False), settings)
492
+ #: A guarded ``redis.asyncio.Connection`` for async pools you build yourself.
493
+ self.async_connection_class = guarded_connection_class(_default_connection(True), settings)
494
+
495
+ def guard_connection_class(self, base: type) -> type:
496
+ """A guarded subclass of another connection class, such as ``redis.SSLConnection``."""
497
+ return guarded_connection_class(base, self._settings)
498
+
499
+ def describe(self) -> dict[str, Any]:
500
+ return {"system": "redis", **({"name": self.name} if self.name else {}), "mode": "guard"}
501
+
502
+
503
+ def _default_connection(asynchronous: bool) -> type:
504
+ if asynchronous:
505
+ from redis.asyncio import Connection
506
+ else:
507
+ from redis import Connection
508
+ return Connection
509
+
510
+
511
+ def redis_store(
512
+ client: Any = None, *, name: Optional[str] = None, treat_as_read: Optional[Iterable[str]] = None,
513
+ ) -> RedisStore:
514
+ """Hook a redis-py client or connection pool in place and return the store for ``data_stores``.
515
+
516
+ ``client`` is a ``redis.Redis``, ``redis.asyncio.Redis``, or a ``ConnectionPool`` or
517
+ ``BlockingConnectionPool`` of either. Pass nothing to get just the store, and build your pool
518
+ with ``store.connection_class`` (or ``store.async_connection_class``). Hooking the same client
519
+ twice is refused, so its commands are never logged twice.
520
+
521
+ Args:
522
+ name: A display label for discovery, such as ``cache``. Never a URL or host name.
523
+ treat_as_read: Commands you state never write, such as a custom module read
524
+ ``MYMODULE.GET``: exact upper-case names (or ``CONTAINER|SUB``), no wildcards.
525
+ **The guard trusts this list**: a listed command that does write is not blocked.
526
+ """
527
+ settings = _Settings(read_set(treat_as_read, lambda item: item.upper()))
528
+ store = RedisStore(store_label(name), settings)
529
+ if client is not None:
530
+ pool = getattr(client, "connection_pool", client)
531
+ if not hasattr(pool, "connection_class"):
532
+ raise TypeError(
533
+ "redis_store takes a redis-py client or connection pool. A Redis Cluster client has a pool per node: "
534
+ "call redis_store(name=...) first and build the cluster with connection_class=store.connection_class.")
535
+ _hook_pool(pool, settings)
536
+ return store