resource-engine 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. resource_engine/__init__.py +96 -0
  2. resource_engine/application/__init__.py +1 -0
  3. resource_engine/application/actions.py +48 -0
  4. resource_engine/application/context.py +111 -0
  5. resource_engine/application/events.py +54 -0
  6. resource_engine/application/hooks.py +272 -0
  7. resource_engine/application/idempotency.py +277 -0
  8. resource_engine/application/manager.py +1987 -0
  9. resource_engine/application/query.py +47 -0
  10. resource_engine/application/registry.py +137 -0
  11. resource_engine/application/relations.py +470 -0
  12. resource_engine/application/resource.py +984 -0
  13. resource_engine/application/searching.py +162 -0
  14. resource_engine/application/settings.py +169 -0
  15. resource_engine/application/slots.py +67 -0
  16. resource_engine/application/state_machines.py +177 -0
  17. resource_engine/application/timers.py +347 -0
  18. resource_engine/application/transaction.py +100 -0
  19. resource_engine/application/views.py +239 -0
  20. resource_engine/audit/__init__.py +40 -0
  21. resource_engine/audit/export.py +280 -0
  22. resource_engine/audit/history.py +165 -0
  23. resource_engine/audit/janitor.py +257 -0
  24. resource_engine/audit/model.py +98 -0
  25. resource_engine/audit/recorder.py +145 -0
  26. resource_engine/audit/resource.py +68 -0
  27. resource_engine/audit/seal.py +327 -0
  28. resource_engine/audit/sink.py +69 -0
  29. resource_engine/authz/__init__.py +72 -0
  30. resource_engine/authz/apikeys.py +300 -0
  31. resource_engine/authz/base.py +143 -0
  32. resource_engine/authz/catalog.py +291 -0
  33. resource_engine/authz/conditions.py +416 -0
  34. resource_engine/authz/config.py +77 -0
  35. resource_engine/authz/evaluator.py +382 -0
  36. resource_engine/authz/external.py +249 -0
  37. resource_engine/authz/fields.py +44 -0
  38. resource_engine/authz/model.py +145 -0
  39. resource_engine/authz/resources.py +289 -0
  40. resource_engine/authz/roles.py +101 -0
  41. resource_engine/cache.py +144 -0
  42. resource_engine/calls.py +100 -0
  43. resource_engine/capabilities.py +145 -0
  44. resource_engine/composite.py +295 -0
  45. resource_engine/documents/__init__.py +69 -0
  46. resource_engine/documents/content.py +57 -0
  47. resource_engine/documents/events.py +49 -0
  48. resource_engine/documents/janitor.py +93 -0
  49. resource_engine/documents/machine.py +38 -0
  50. resource_engine/documents/manager.py +704 -0
  51. resource_engine/documents/model.py +91 -0
  52. resource_engine/documents/pipeline.py +98 -0
  53. resource_engine/documents/processors.py +320 -0
  54. resource_engine/documents/resource.py +39 -0
  55. resource_engine/domain/__init__.py +10 -0
  56. resource_engine/domain/events.py +50 -0
  57. resource_engine/domain/exceptions.py +23 -0
  58. resource_engine/email.py +417 -0
  59. resource_engine/errors.py +562 -0
  60. resource_engine/explorer.py +133 -0
  61. resource_engine/exports.py +687 -0
  62. resource_engine/generation.py +233 -0
  63. resource_engine/i18n.py +251 -0
  64. resource_engine/identity.py +46 -0
  65. resource_engine/integration.py +80 -0
  66. resource_engine/jobs.py +390 -0
  67. resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
  68. resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
  69. resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
  70. resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
  71. resource_engine/logs.py +201 -0
  72. resource_engine/messaging/__init__.py +73 -0
  73. resource_engine/messaging/asyncapi.py +529 -0
  74. resource_engine/messaging/cloudevents.py +98 -0
  75. resource_engine/messaging/consumer.py +165 -0
  76. resource_engine/messaging/delivery.py +115 -0
  77. resource_engine/messaging/envelope.py +193 -0
  78. resource_engine/messaging/hub.py +148 -0
  79. resource_engine/messaging/inbound.py +76 -0
  80. resource_engine/messaging/inspection.py +113 -0
  81. resource_engine/messaging/janitor.py +136 -0
  82. resource_engine/messaging/live.py +179 -0
  83. resource_engine/messaging/processing.py +357 -0
  84. resource_engine/messaging/publishing.py +318 -0
  85. resource_engine/messaging/relay.py +84 -0
  86. resource_engine/messaging/worker.py +166 -0
  87. resource_engine/nosql.py +394 -0
  88. resource_engine/ports/__init__.py +13 -0
  89. resource_engine/ports/activity.py +171 -0
  90. resource_engine/ports/audit.py +42 -0
  91. resource_engine/ports/authz.py +132 -0
  92. resource_engine/ports/cache.py +41 -0
  93. resource_engine/ports/email.py +118 -0
  94. resource_engine/ports/event_publisher.py +34 -0
  95. resource_engine/ports/idempotency.py +69 -0
  96. resource_engine/ports/identity.py +112 -0
  97. resource_engine/ports/locks.py +28 -0
  98. resource_engine/ports/messaging.py +197 -0
  99. resource_engine/ports/observability.py +60 -0
  100. resource_engine/ports/ratelimit.py +59 -0
  101. resource_engine/ports/repository.py +56 -0
  102. resource_engine/ports/storage.py +93 -0
  103. resource_engine/ports/templates.py +54 -0
  104. resource_engine/ports/tracing.py +61 -0
  105. resource_engine/ports/unit_of_work.py +46 -0
  106. resource_engine/processes.py +408 -0
  107. resource_engine/py.typed +0 -0
  108. resource_engine/querying.py +319 -0
  109. resource_engine/ratelimit.py +217 -0
  110. resource_engine/reporting.py +230 -0
  111. resource_engine/schema_examples.py +51 -0
  112. resource_engine/templates.py +143 -0
  113. resource_engine/tenancy.py +68 -0
  114. resource_engine/testing/__init__.py +34 -0
  115. resource_engine/testing/activity.py +123 -0
  116. resource_engine/testing/contracts.py +1416 -0
  117. resource_engine/testing/email.py +36 -0
  118. resource_engine/testing/engine.py +40 -0
  119. resource_engine/testing/memory.py +603 -0
  120. resource_engine/testing/storage.py +110 -0
  121. resource_engine/testing/tracing.py +100 -0
  122. resource_engine/tracing.py +156 -0
  123. resource_engine/translatable.py +80 -0
  124. resource_engine/versions.py +189 -0
  125. resource_engine-0.1.0.dist-info/METADATA +36 -0
  126. resource_engine-0.1.0.dist-info/RECORD +128 -0
  127. resource_engine-0.1.0.dist-info/WHEEL +4 -0
  128. resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,319 @@
1
+ """Read-only resources over analytical query engines (Athena, BigQuery, Trino):
2
+ data lake tables served as view resources with the usual filters, sorting,
3
+ paging, row-level permissions and tenancy.
4
+
5
+ ```python
6
+ from resource_engine.querying import QueryEngineStore
7
+ from resource_engine_http import TrinoEngine
8
+
9
+ store = QueryEngineStore(TrinoEngine(http, "http://trino:8080", catalog="lake"), registry,
10
+ tables={"sales": "lake.sales.daily"})
11
+ manager = ResourceManager(registry, store.unit_of_work)
12
+ ```
13
+
14
+ - **Compiled queries:** ``list`` becomes one ``SELECT`` with ``WHERE``
15
+ (filters, the row filter and the tenant, from the condition language),
16
+ ``ORDER BY`` and the dialect's paging, plus one ``COUNT(*)``. Values are
17
+ always parameters, never pasted into the SQL.
18
+ - **Read-only:** writes raise ``OperationNotEnabled``; declare the resource
19
+ with ``operations = ["list", "get"]`` (a view).
20
+ - **Engines:** the ``QueryEngine`` port. ``TrinoEngine`` and
21
+ ``BigQueryEngine`` (``resource-engine-http``), ``AthenaEngine``
22
+ (``resource-engine-aws``). Engines with a SQLAlchemy dialect (Synapse
23
+ serverless, Databricks SQL, Snowflake) are already served by
24
+ ``resource-engine-sqlalchemy``'s ``map_view``.
25
+ - **Cost:** every engine adapter takes a limit (bytes scanned or billed) and a
26
+ timeout; results can be cached with ``Resource.cache_ttl`` and the ``Cache``
27
+ port like any record.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import dataclasses
33
+ import math
34
+ import typing
35
+ from collections.abc import Mapping, Sequence
36
+ from dataclasses import dataclass
37
+ from typing import Any, Literal, Protocol
38
+
39
+ from resource_engine.application.query import ListQuery, Page
40
+ from resource_engine.errors import ConditionNotSupported, OperationNotEnabled
41
+
42
+ type Row = dict[str, Any]
43
+
44
+
45
+ class QueryEngine(Protocol):
46
+ """Runs a read-only SQL query with positional ``?`` parameters."""
47
+
48
+ dialect: Dialect
49
+
50
+ async def query(self, sql: str, params: Sequence[Any]) -> list[Row]:
51
+ """The rows, as dicts by column name. Raises ``RemoteCallFailed``
52
+ (RE-E501) when the engine fails or a limit is hit."""
53
+ ...
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Dialect:
58
+ """How an engine writes identifiers, paging and list membership."""
59
+
60
+ name: str
61
+ quote: str = '"'
62
+ paging: Literal["offset_limit", "limit_offset"] = "offset_limit"
63
+ array_contains: str = "contains({column}, {value})"
64
+ #: Case-insensitive "holds this text"; ``value`` is a ``%...%`` pattern,
65
+ #: lowercased, with ``%``, ``_`` and ``\\`` escaped by a backslash.
66
+ text_contains: str = "LOWER({column}) LIKE {value} ESCAPE '\\'"
67
+
68
+ def identifier(self, name: str) -> str:
69
+ """``name`` checked and quoted. Raises ``ConditionNotSupported`` for unsafe names."""
70
+ if not all(part.replace("_", "").isalnum() for part in name.split(".")):
71
+ raise ConditionNotSupported(f"Unsafe identifier {name!r}")
72
+ q = self.quote
73
+ return ".".join(f"{q}{part}{q}" for part in name.split("."))
74
+
75
+ def page(self, offset: int, limit: int) -> str:
76
+ """The paging clause."""
77
+ if self.paging == "limit_offset":
78
+ return f" LIMIT {int(limit)} OFFSET {int(offset)}"
79
+ return f" OFFSET {int(offset)} LIMIT {int(limit)}"
80
+
81
+
82
+ #: Trino, Presto and Athena (engine v3).
83
+ TRINO = Dialect("trino")
84
+ #: Google BigQuery (GoogleSQL).
85
+ BIGQUERY = Dialect(
86
+ "bigquery",
87
+ quote="`",
88
+ paging="limit_offset",
89
+ array_contains="{value} IN UNNEST({column})",
90
+ text_contains="LOWER({column}) LIKE {value}", # a backslash escapes by default
91
+ )
92
+
93
+ _COMPARISONS = {"eq": "=", "ne": "<>", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
94
+
95
+
96
+ class Compiler:
97
+ """The condition language and ``ListQuery`` as SQL with ``?`` parameters."""
98
+
99
+ def __init__(self, dialect: Dialect) -> None:
100
+ self.dialect = dialect
101
+ self.params: list[Any] = []
102
+
103
+ def _value(self, value: Any) -> str:
104
+ if isinstance(value, float) and not math.isfinite(value):
105
+ # engines that take literals would read nan/inf as a column name
106
+ raise ConditionNotSupported(f"{value!r} is not a number a query can compare with")
107
+ self.params.append(value)
108
+ return "?"
109
+
110
+ def _operand(self, node: Any) -> tuple[str, bool]:
111
+ """SQL of an operand, and whether it is a column."""
112
+ if isinstance(node, Mapping) and "attr" in node:
113
+ path = str(node["attr"])
114
+ if not path.startswith("resource."):
115
+ raise ConditionNotSupported(f"Only record attributes can be queried, not {path!r}")
116
+ return self.dialect.identifier(path.removeprefix("resource.")), True
117
+ return self._value(node), False
118
+
119
+ def condition(self, node: Any) -> str:
120
+ """The SQL for a condition; its values go to ``params``."""
121
+ if node is True:
122
+ return "1 = 1"
123
+ if node is False:
124
+ return "1 = 0"
125
+ if not isinstance(node, Mapping) or len(node) != 1:
126
+ raise ConditionNotSupported(f"Unsupported condition {node!r}")
127
+ op, args = next(iter(node.items()))
128
+ if op in ("and", "or"):
129
+ parts = [self.condition(a) for a in args]
130
+ if not parts:
131
+ return "1 = 1" if op == "and" else "1 = 0"
132
+ return "(" + f" {op.upper()} ".join(parts) + ")"
133
+ if op == "not":
134
+ return f"(NOT {self.condition(args)})"
135
+ if op == "exists":
136
+ column, _ = self._operand(args)
137
+ return f"{column} IS NOT NULL"
138
+ if op in _COMPARISONS:
139
+ left, right = args
140
+ if right is None or left is None:
141
+ column, _ = self._operand(left if right is None else right)
142
+ return f"{column} IS {'NOT ' if op == 'ne' else ''}NULL"
143
+ return f"{self._operand(left)[0]} {_COMPARISONS[op]} {self._operand(right)[0]}"
144
+ if op in ("in", "nin"):
145
+ left, values = args
146
+ column, _ = self._operand(left)
147
+ if not values:
148
+ return "1 = 0" if op == "in" else "1 = 1"
149
+ listed = ", ".join(self._value(v) for v in values)
150
+ return f"{column} {'NOT IN' if op == 'nin' else 'IN'} ({listed})"
151
+ if op == "contains":
152
+ collection, item = args
153
+ column, _ = self._operand(collection)
154
+ return self.dialect.array_contains.format(column=column, value=self._value(item))
155
+ if op == "icontains":
156
+ text_field, text = args
157
+ if not isinstance(text, str):
158
+ raise ConditionNotSupported("'icontains' needs literal text")
159
+ from resource_engine.application.searching import like_pattern
160
+
161
+ column, _ = self._operand(text_field)
162
+ pattern = self._value(like_pattern(text.lower()))
163
+ return self.dialect.text_contains.format(column=column, value=pattern)
164
+ raise ConditionNotSupported(f"Unsupported operator {op!r} for a query engine")
165
+
166
+ def where(self, query: ListQuery) -> str:
167
+ """The ``WHERE`` clause of ``query``'s filters and condition (empty when none)."""
168
+ parts = []
169
+ for name, value in query.filters.items():
170
+ if "." in name:
171
+ raise ConditionNotSupported(
172
+ f"Related filters ({name}) are not available on query-engine resources"
173
+ )
174
+ parts.append(self.condition({"eq": [{"attr": f"resource.{name}"}, value]}))
175
+ if query.condition is not None:
176
+ parts.append(self.condition(query.condition))
177
+ return f" WHERE {' AND '.join(parts)}" if parts else ""
178
+
179
+ def order(self, query: ListQuery, default: str | None) -> str:
180
+ """``ORDER BY`` the query's fields, then ``default`` (the id) to break
181
+ ties, so pages never repeat or skip rows."""
182
+ items = list(query.order_by)
183
+ if default and default not in {o.lstrip("-") for o in items}:
184
+ items.append(default)
185
+ if not items:
186
+ return ""
187
+ rendered = [
188
+ f"{self.dialect.identifier(o.lstrip('-'))} {'DESC' if o.startswith('-') else 'ASC'}"
189
+ for o in items
190
+ ]
191
+ return " ORDER BY " + ", ".join(rendered)
192
+
193
+
194
+ def _columns(model: type) -> list[str]:
195
+ if dataclasses.is_dataclass(model):
196
+ return [f.name for f in dataclasses.fields(model)]
197
+ if hasattr(model, "model_fields"):
198
+ return list(model.model_fields)
199
+ return list(typing.get_type_hints(model))
200
+
201
+
202
+ class QueryEngineRepository:
203
+ """A read-only ``Repository`` over one table of a ``QueryEngine``."""
204
+
205
+ supports_conditions = True
206
+ supports_versions = False
207
+
208
+ def __init__(
209
+ self, engine: QueryEngine, table: str, model: type, *, id_field: str = "id"
210
+ ) -> None:
211
+ self.engine = engine
212
+ self.table = table
213
+ self.model = model
214
+ self.id_field = id_field
215
+ self.columns = _columns(model)
216
+
217
+ def _select(self, compiler: Compiler) -> str:
218
+ names = ", ".join(compiler.dialect.identifier(c) for c in self.columns)
219
+ return f"SELECT {names} FROM {compiler.dialect.identifier(self.table)}" # noqa: S608 - identifiers checked and quoted; values are parameters
220
+
221
+ def _entity(self, row: Row) -> Any:
222
+ return self.model(**{c: row.get(c) for c in self.columns})
223
+
224
+ async def get(self, entity_id: Any) -> Any:
225
+ """The row with ``entity_id``, or ``None``."""
226
+ compiler = Compiler(self.engine.dialect)
227
+ where = compiler.condition({"eq": [{"attr": f"resource.{self.id_field}"}, entity_id]})
228
+ rows = await self.engine.query(
229
+ f"{self._select(compiler)} WHERE {where}{compiler.dialect.page(0, 1)}",
230
+ compiler.params,
231
+ )
232
+ return self._entity(rows[0]) if rows else None
233
+
234
+ async def list(self, query: ListQuery) -> Page[Any]:
235
+ # both statements are built first: a refused name or value runs no query
236
+ """One page of the rows matching ``query``, with the total."""
237
+ counter = Compiler(self.engine.dialect)
238
+ where = counter.where(query)
239
+ count = f"SELECT COUNT(*) AS total FROM {counter.dialect.identifier(self.table)}{where}" # noqa: S608 - identifiers checked and quoted; values are parameters
240
+ compiler = Compiler(self.engine.dialect)
241
+ sql = (
242
+ self._select(compiler)
243
+ + compiler.where(query)
244
+ + compiler.order(query, self.id_field if self.id_field in self.columns else None)
245
+ + compiler.dialect.page(query.offset, query.limit)
246
+ )
247
+ total_rows = await self.engine.query(count, counter.params)
248
+ total = int(next(iter(total_rows[0].values()))) if total_rows else 0
249
+ rows = await self.engine.query(sql, compiler.params)
250
+ return Page([self._entity(r) for r in rows], total, query.offset, query.limit)
251
+
252
+ async def _read_only(self, *args: Any, **kw: Any) -> Any:
253
+ raise OperationNotEnabled(
254
+ f"{self.table} is read-only: it is served by a query engine",
255
+ hint="Declare the resource with operations = ['list', 'get'].",
256
+ )
257
+
258
+ add = update = delete = _read_only
259
+
260
+
261
+ class QueryEngineUnitOfWork:
262
+ """Hands out the query-engine repositories; there is nothing to commit."""
263
+
264
+ def __init__(self, repositories: Mapping[str, QueryEngineRepository]) -> None:
265
+ self.repositories = repositories
266
+
267
+ def repository(self, resource_name: str) -> QueryEngineRepository:
268
+ """The repository of ``resource_name``."""
269
+ return self.repositories[resource_name]
270
+
271
+ async def commit(self) -> None:
272
+ """Nothing to commit: query engines are read-only."""
273
+ return None
274
+
275
+ async def rollback(self) -> None:
276
+ """Nothing to roll back."""
277
+ return None
278
+
279
+ async def __aenter__(self) -> QueryEngineUnitOfWork:
280
+ return self
281
+
282
+ async def __aexit__(self, *exc: Any) -> None:
283
+ return None
284
+
285
+
286
+ class QueryEngineStore:
287
+ """Read-only resources served by a query engine.
288
+
289
+ Args:
290
+ engine: The ``QueryEngine``.
291
+ registry: The registry; its resources named in ``tables`` are served.
292
+ tables: Resource name → table (``catalog.schema.table`` for Trino,
293
+ ``dataset.table`` for BigQuery, ``database.table`` for Athena).
294
+ """
295
+
296
+ def __init__(self, engine: QueryEngine, registry: Any, tables: Mapping[str, str]) -> None:
297
+ self.engine = engine
298
+ self.repositories = {}
299
+ for name, table in tables.items():
300
+ definition = registry.get(name)
301
+ self.repositories[name] = QueryEngineRepository(
302
+ engine, table, definition.model, id_field=definition.id_field
303
+ )
304
+
305
+ def unit_of_work(self) -> QueryEngineUnitOfWork:
306
+ """A unit of work over the store's repositories."""
307
+ return QueryEngineUnitOfWork(self.repositories)
308
+
309
+
310
+ __all__ = [
311
+ "BIGQUERY",
312
+ "TRINO",
313
+ "Compiler",
314
+ "Dialect",
315
+ "QueryEngine",
316
+ "QueryEngineRepository",
317
+ "QueryEngineStore",
318
+ "QueryEngineUnitOfWork",
319
+ ]
@@ -0,0 +1,217 @@
1
+ """Rate limiting: how many requests a caller may make per time window.
2
+
3
+ ```python
4
+ limiter = SlidingWindowLimiter(
5
+ InMemoryRateLimitStore(), # one instance; RedisRateLimitStore to share
6
+ default=Limit(600, per=60), # per authenticated caller (principal or API key)
7
+ anonymous=Limit(60, per=60), # per client IP, without credentials
8
+ failed_auth=Limit(10, per=300), # failed authentications per IP (brute force)
9
+ actions={"invoices:create": Limit(20, per=60), "*:action:*": Limit(30, per=60)},
10
+ )
11
+ ResourceManager(..., rate_limiter=limiter) # per action, every adapter
12
+ bearer_actor(authenticator, rate_limiter=limiter) # per caller, HTTP
13
+ ```
14
+
15
+ Counting uses a sliding window: the current fixed window's hits plus the
16
+ previous window's, weighted by how much of it still overlaps. It's accurate
17
+ to a few percent, costs one round trip per check, and never resets in a
18
+ burst at a window boundary. Refused requests count too, so a client that keeps
19
+ hammering stays refused. ``RateLimiter`` is the port
20
+ (``resource_engine.ports.ratelimit``): implement it to delegate elsewhere.
21
+ See docs/rate-limits.md.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import math
27
+ import time
28
+ from collections.abc import Callable, Mapping
29
+ from dataclasses import dataclass, field
30
+ from datetime import timedelta
31
+ from typing import Any, Protocol, override
32
+
33
+ from resource_engine.errors import RateLimited
34
+ from resource_engine.ports.ratelimit import Decision, RateLimiter
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Limit:
39
+ """At most ``requests`` per ``per`` seconds (or a ``timedelta``)."""
40
+
41
+ requests: int
42
+ per: float | timedelta = 60
43
+
44
+ @property
45
+ def window(self) -> float:
46
+ """The window in seconds."""
47
+ return self.per.total_seconds() if isinstance(self.per, timedelta) else float(self.per)
48
+
49
+ def __post_init__(self) -> None:
50
+ if self.requests < 1 or self.window <= 0:
51
+ raise ValueError("A limit needs requests >= 1 and a positive window")
52
+
53
+
54
+ class RateLimitStore(Protocol):
55
+ """Counters per key and window (shared between instances to limit globally)."""
56
+
57
+ async def hit(self, key: str, window: int, ttl: int, amount: int = 1) -> tuple[int, int]:
58
+ """Add ``amount`` (0 reads) to ``key``'s counter for ``window`` (an index)
59
+ and return it with the counter of ``window - 1``. Counters expire after
60
+ ``ttl`` seconds."""
61
+ ...
62
+
63
+
64
+ class InMemoryRateLimitStore(RateLimitStore):
65
+ """Counters in this process (one instance, development and tests)."""
66
+
67
+ def __init__(self) -> None:
68
+ self._counts: dict[tuple[str, int], int] = {}
69
+ self._expiry: dict[tuple[str, int], float] = {}
70
+
71
+ @override
72
+ async def hit(self, key: str, window: int, ttl: int, amount: int = 1) -> tuple[int, int]:
73
+ now = time.monotonic()
74
+ if len(self._expiry) > 10_000: # forget expired windows now and then
75
+ for k in [k for k, at in self._expiry.items() if at <= now]:
76
+ self._counts.pop(k, None)
77
+ self._expiry.pop(k, None)
78
+ current = self._counts.get((key, window), 0) + amount
79
+ if amount:
80
+ self._counts[(key, window)] = current
81
+ self._expiry.setdefault((key, window), now + ttl)
82
+ return current, self._counts.get((key, window - 1), 0)
83
+
84
+
85
+ @dataclass
86
+ class SlidingWindowLimiter:
87
+ """The built-in ``RateLimiter``: limits per caller, address and action, with
88
+ sliding-window counters kept in a ``RateLimitStore``.
89
+
90
+ Args:
91
+ store: Where counters live.
92
+ default: Per authenticated caller, for every request.
93
+ anonymous: Per client IP, for requests without credentials.
94
+ failed_auth: Failed authentications per client IP. Once reached, the
95
+ IP's credentials are not even checked until the window frees up.
96
+ actions: Per caller and engine action (``invoices:create``, patterns
97
+ like ``invoices:*`` or ``*:action:*``), checked by the manager for
98
+ every adapter. Each matching pattern is a limit of its own.
99
+ exempt: Callers never limited (``lambda principal: principal.has_role(...)``).
100
+ The engine's own system principals (jobs, consumers) always are.
101
+ prefix: Key prefix in the store.
102
+ """
103
+
104
+ store: RateLimitStore
105
+ default: Limit | None = None
106
+ anonymous: Limit | None = None
107
+ failed_auth: Limit | None = None
108
+ actions: Mapping[str, Limit] = field(default_factory=dict)
109
+ exempt: Callable[[Any], bool] | None = None
110
+ prefix: str = "re:rl:"
111
+ clock: Callable[[], float] = time.time
112
+
113
+ async def check(self, key: str, limit: Limit, *, count: bool = True) -> Decision:
114
+ """Count one request for ``key`` (``count=False`` only looks) and decide."""
115
+ window = limit.window
116
+ now = self.clock()
117
+ index = int(now // window)
118
+ elapsed = now - index * window
119
+ current, previous = await self.store.hit(
120
+ f"{self.prefix}{key}:{int(window)}",
121
+ index,
122
+ ttl=math.ceil(window * 2),
123
+ amount=1 if count else 0,
124
+ )
125
+ used = previous * (1 - elapsed / window) + current
126
+ # looking: the next request would add one
127
+ allowed = used <= limit.requests if count else used + 1 <= limit.requests
128
+ reset = math.ceil(window - elapsed)
129
+ retry = 0
130
+ if not allowed:
131
+ # until the previous window's weighted share has dropped enough
132
+ excess = used - limit.requests + (0 if count else 1)
133
+ retry = math.ceil(min(excess / previous * window, reset)) if previous else reset
134
+ retry = max(retry, 1)
135
+ return Decision(
136
+ allowed=allowed,
137
+ limit=limit.requests,
138
+ remaining=max(0, int(limit.requests - used)),
139
+ reset=reset,
140
+ retry_after=retry,
141
+ key=key,
142
+ )
143
+
144
+ async def enforce(self, key: str, limit: Limit, *, what: str, count: bool = True) -> Decision:
145
+ """Count a request against ``limit`` and raise ``RateLimited`` past it."""
146
+ decision = await self.check(key, limit, count=count)
147
+ if not decision.allowed:
148
+ raise RateLimited(
149
+ f"Too many {what}: try again in {decision.retry_after} s",
150
+ hint="Slow down; Retry-After says when to retry.",
151
+ details={
152
+ "limit": decision.limit,
153
+ "window": int(limit.window),
154
+ "retry_after": decision.retry_after,
155
+ "scope": what,
156
+ },
157
+ )
158
+ return decision
159
+
160
+ def is_exempt(self, actor: Any) -> bool:
161
+ """Whether ``actor`` is never limited (system principals)."""
162
+ from resource_engine.authz.base import SystemPrincipal
163
+
164
+ if isinstance(actor, SystemPrincipal):
165
+ return True
166
+ return bool(self.exempt and actor is not None and self.exempt(actor))
167
+
168
+ async def caller(self, actor: Any) -> Decision | None:
169
+ """The ``default`` limit of an authenticated caller."""
170
+ if self.default is None or actor is None or self.is_exempt(actor):
171
+ return None
172
+ return await self.enforce(f"caller:{_id(actor)}", self.default, what="requests")
173
+
174
+ async def client(self, address: str | None) -> Decision | None:
175
+ """The ``anonymous`` limit of a client without credentials."""
176
+ if self.anonymous is None:
177
+ return None
178
+ return await self.enforce(f"ip:{address or 'unknown'}", self.anonymous, what="requests")
179
+
180
+ async def before_auth(self, address: str | None) -> None:
181
+ """Refuse an address that already failed authentication too often."""
182
+ if self.failed_auth is not None:
183
+ await self.enforce(
184
+ f"auth:{address or 'unknown'}",
185
+ self.failed_auth,
186
+ what="failed authentications",
187
+ count=False,
188
+ )
189
+
190
+ async def failed(self, address: str | None) -> None:
191
+ """Count one failed authentication of ``address``."""
192
+ if self.failed_auth is not None:
193
+ await self.check(f"auth:{address or 'unknown'}", self.failed_auth)
194
+
195
+ async def action(self, actor: Any, action: str) -> None:
196
+ """Every ``actions`` limit matching ``action``, for this caller."""
197
+ if not self.actions or self.is_exempt(actor):
198
+ return
199
+ from resource_engine.authz.catalog import action_matches
200
+
201
+ for pattern, limit in self.actions.items():
202
+ if action_matches(pattern, action):
203
+ await self.enforce(f"action:{pattern}:{_id(actor)}", limit, what=action)
204
+
205
+
206
+ def _id(actor: Any) -> str:
207
+ return str(getattr(actor, "id", None) or "anonymous")
208
+
209
+
210
+ __all__ = [
211
+ "Decision",
212
+ "InMemoryRateLimitStore",
213
+ "Limit",
214
+ "RateLimitStore",
215
+ "RateLimiter",
216
+ "SlidingWindowLimiter",
217
+ ]