idempotency-asgi 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.
@@ -0,0 +1,4 @@
1
+ from idempotency_asgi.middleware import IdempotencyMiddleware
2
+
3
+ __all__ = ["IdempotencyMiddleware"]
4
+ __version__ = "0.1.0"
@@ -0,0 +1,8 @@
1
+ from collections.abc import Awaitable, Callable, MutableMapping
2
+ from typing import Any
3
+
4
+ Scope = MutableMapping[str, Any]
5
+ Message = MutableMapping[str, Any]
6
+ Receive = Callable[[], Awaitable[Message]]
7
+ Send = Callable[[Message], Awaitable[None]]
8
+ ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import logging
6
+ from typing import Protocol
7
+
8
+ logger = logging.getLogger("idempotency_asgi")
9
+
10
+
11
+ class Purgeable(Protocol):
12
+ async def purge_expired(self) -> int: ...
13
+
14
+
15
+ async def run_cleanup_loop(storage: Purgeable, interval_seconds: float = 300) -> None:
16
+ """Periodically delete expired keys until cancelled."""
17
+ while True:
18
+ try:
19
+ deleted = await storage.purge_expired()
20
+ if deleted:
21
+ logger.info("purged %d expired idempotency keys", deleted)
22
+ except asyncio.CancelledError:
23
+ raise
24
+ except Exception:
25
+ # Ошибка чистки не должна ронять приложение.
26
+ logger.exception("idempotency cleanup failed")
27
+ await asyncio.sleep(interval_seconds)
28
+
29
+
30
+ @contextlib.asynccontextmanager
31
+ async def cleanup_task(storage: Purgeable, interval_seconds: float = 300): # type: ignore[no-untyped-def]
32
+ """Run the cleanup loop in the background for the duration of the context."""
33
+ task = asyncio.create_task(run_cleanup_loop(storage, interval_seconds))
34
+ try:
35
+ yield
36
+ finally:
37
+ task.cancel()
38
+ with contextlib.suppress(asyncio.CancelledError):
39
+ await task
@@ -0,0 +1,218 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from collections.abc import Callable
6
+ from contextlib import suppress
7
+ from dataclasses import dataclass, field
8
+ from urllib.parse import parse_qsl
9
+
10
+ from idempotency_asgi._types import ASGIApp, Message, Receive, Scope, Send
11
+ from idempotency_asgi.storage import ClaimStatus, Storage, StoredResponse
12
+
13
+ HEADER_NAME = b"idempotency-key"
14
+ SENSITIVE_HEADERS = frozenset({"authorization", "set-cookie", "proxy-authenticate", "cookie"})
15
+ UNSAFE_METHODS = frozenset({"POST", "PATCH"})
16
+
17
+ ScopeGetter = Callable[[Scope], str]
18
+
19
+
20
+ def _default_scope_getter(scope: Scope) -> str:
21
+ return "global"
22
+
23
+
24
+ @dataclass
25
+ class _Capture:
26
+ """Что мы запомнили из ответа приложения."""
27
+
28
+ start: Message | None = None
29
+ held: Message | None = None # последнее сообщение, отправим после сохранения
30
+ chunks: list[bytes] = field(default_factory=list)
31
+ size: int = 0
32
+ storable: bool = True
33
+
34
+
35
+ class IdempotencyMiddleware:
36
+ """Pure ASGI middleware that makes POST/PATCH requests idempotent."""
37
+
38
+ def __init__(
39
+ self,
40
+ app: ASGIApp,
41
+ storage: Storage,
42
+ *,
43
+ scope_getter: ScopeGetter = _default_scope_getter,
44
+ lock_seconds: int = 30,
45
+ ttl_seconds: int = 24 * 3600,
46
+ max_body_bytes: int = 1_000_000,
47
+ max_response_bytes: int = 1_000_000,
48
+ require_key: bool = False,
49
+ ) -> None:
50
+ self.app = app
51
+ self.storage = storage
52
+ self.scope_getter = scope_getter
53
+ self.lock_seconds = lock_seconds
54
+ self.ttl_seconds = ttl_seconds
55
+ self.max_body_bytes = max_body_bytes
56
+ self.max_response_bytes = max_response_bytes
57
+ self.require_key = require_key
58
+
59
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
60
+ if scope["type"] != "http" or scope["method"] not in UNSAFE_METHODS:
61
+ await self.app(scope, receive, send)
62
+ return
63
+
64
+ key = _get_header(scope, HEADER_NAME)
65
+ if key is None:
66
+ if self.require_key:
67
+ await _send_json(send, 400, {"detail": "Idempotency-Key header is required"})
68
+ else:
69
+ await self.app(scope, receive, send)
70
+ return
71
+
72
+ body = await _read_body(receive, self.max_body_bytes)
73
+ if body is None:
74
+ await _send_json(send, 413, {"detail": "Request body too large"})
75
+ return
76
+
77
+ fingerprint = _fingerprint(scope, body)
78
+ owner = self.scope_getter(scope)
79
+
80
+ result = await self.storage.claim(
81
+ owner, key, fingerprint, self.lock_seconds, self.ttl_seconds
82
+ )
83
+
84
+ if result.status is ClaimStatus.REPLAY and result.response is not None:
85
+ await _send_stored(send, result.response)
86
+ return
87
+ if result.status is ClaimStatus.IN_PROGRESS:
88
+ await _send_json(
89
+ send,
90
+ 409,
91
+ {"detail": "A request with this Idempotency-Key is still in progress"},
92
+ extra_headers=[(b"retry-after", str(result.retry_after or 1).encode())],
93
+ )
94
+ return
95
+ if result.status is ClaimStatus.MISMATCH:
96
+ await _send_json(
97
+ send,
98
+ 422,
99
+ {"detail": "Idempotency-Key was already used with a different request"},
100
+ )
101
+ return
102
+
103
+ await self._run_and_store(scope, receive, send, owner, key, body)
104
+
105
+ async def _run_and_store(
106
+ self, scope: Scope, receive: Receive, send: Send, owner: str, key: str, body: bytes
107
+ ) -> None:
108
+ replayed = False
109
+
110
+ async def replay_receive() -> Message:
111
+ nonlocal replayed
112
+ if not replayed:
113
+ replayed = True
114
+ return {"type": "http.request", "body": body, "more_body": False}
115
+ return await receive()
116
+
117
+ cap = _Capture()
118
+
119
+ async def capture_send(message: Message) -> None:
120
+ if message["type"] == "http.response.start":
121
+ cap.start = message
122
+ elif message["type"] == "http.response.body":
123
+ chunk = message.get("body", b"")
124
+ more = message.get("more_body", False)
125
+ cap.size += len(chunk)
126
+ if more or cap.size > self.max_response_bytes:
127
+ cap.storable = False # стрим или слишком большой ответ
128
+ cap.chunks.clear()
129
+ elif cap.storable:
130
+ cap.chunks.append(chunk)
131
+ if not more:
132
+ cap.held = message # отправим после сохранения
133
+ return
134
+ await send(message)
135
+
136
+ try:
137
+ await self.app(scope, replay_receive, capture_send)
138
+ except BaseException:
139
+ await self.storage.release(owner, key)
140
+ raise
141
+
142
+ start = cap.start
143
+ if start is not None and cap.storable and int(start["status"]) < 500:
144
+ headers = [
145
+ (k.decode("latin-1"), v.decode("latin-1"))
146
+ for k, v in start.get("headers", [])
147
+ if k.decode("latin-1").lower() not in SENSITIVE_HEADERS
148
+ ]
149
+ stored = StoredResponse(int(start["status"]), headers, b"".join(cap.chunks))
150
+ try:
151
+ await self.storage.complete(owner, key, stored)
152
+ except Exception:
153
+ # Действие уже выполнено: клиент должен получить ответ в любом случае.
154
+ with suppress(Exception):
155
+ await self.storage.release(owner, key)
156
+ else:
157
+ # 5xx, стрим, слишком большой ответ или ответа нет: не сохраняем.
158
+ await self.storage.release(owner, key)
159
+
160
+ if cap.held is not None:
161
+ await send(cap.held)
162
+
163
+
164
+ def _get_header(scope: Scope, name: bytes) -> str | None:
165
+ for k, v in scope.get("headers", []):
166
+ if k.lower() == name:
167
+ return str(v.decode("latin-1"))
168
+ return None
169
+
170
+
171
+ async def _read_body(receive: Receive, limit: int) -> bytes | None:
172
+ chunks: list[bytes] = []
173
+ size = 0
174
+ while True:
175
+ message = await receive()
176
+ if message["type"] != "http.request":
177
+ return b"".join(chunks)
178
+ chunk = message.get("body", b"")
179
+ size += len(chunk)
180
+ if size > limit:
181
+ return None
182
+ chunks.append(chunk)
183
+ if not message.get("more_body", False):
184
+ return b"".join(chunks)
185
+
186
+
187
+ def _fingerprint(scope: Scope, body: bytes) -> bytes:
188
+ query = sorted(parse_qsl(scope.get("query_string", b"").decode("latin-1")))
189
+ parts = [scope["method"], scope["path"], json.dumps(query), ""]
190
+ h = hashlib.sha256()
191
+ h.update("\n".join(parts).encode())
192
+ h.update(body)
193
+ return h.digest()
194
+
195
+
196
+ async def _send_stored(send: Send, response: StoredResponse) -> None:
197
+ headers = [(k.encode("latin-1"), v.encode("latin-1")) for k, v in response.headers]
198
+ headers = [(k, v) for k, v in headers if k.lower() != b"content-length"]
199
+ headers.append((b"content-length", str(len(response.body)).encode()))
200
+ headers.append((b"idempotency-replayed", b"true"))
201
+ await send({"type": "http.response.start", "status": response.status, "headers": headers})
202
+ await send({"type": "http.response.body", "body": response.body})
203
+
204
+
205
+ async def _send_json(
206
+ send: Send,
207
+ status: int,
208
+ payload: dict[str, str],
209
+ extra_headers: list[tuple[bytes, bytes]] | None = None,
210
+ ) -> None:
211
+ body = json.dumps(payload).encode()
212
+ headers = [
213
+ (b"content-type", b"application/json"),
214
+ (b"content-length", str(len(body)).encode()),
215
+ *(extra_headers or []),
216
+ ]
217
+ await send({"type": "http.response.start", "status": status, "headers": headers})
218
+ await send({"type": "http.response.body", "body": body})
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ import asyncpg
6
+
7
+ from idempotency_asgi.storage import ClaimResult, ClaimStatus, StoredResponse
8
+
9
+ SCHEMA = """
10
+ CREATE TABLE IF NOT EXISTS idempotency_keys (
11
+ scope text NOT NULL,
12
+ key text NOT NULL,
13
+ fingerprint bytea NOT NULL,
14
+ state text NOT NULL CHECK (state IN ('in_progress', 'completed')),
15
+ locked_until timestamptz NOT NULL,
16
+ response_status integer,
17
+ response_headers jsonb,
18
+ response_body bytea,
19
+ created_at timestamptz NOT NULL DEFAULT now(),
20
+ expires_at timestamptz NOT NULL,
21
+ PRIMARY KEY (scope, key)
22
+ );
23
+ CREATE INDEX IF NOT EXISTS idempotency_keys_expires_at_idx
24
+ ON idempotency_keys (expires_at);
25
+ """
26
+
27
+ DELETE_EXPIRED = """
28
+ DELETE FROM idempotency_keys WHERE scope = $1 AND key = $2 AND expires_at < now()
29
+ """
30
+
31
+ INSERT_NEW = """
32
+ INSERT INTO idempotency_keys (scope, key, fingerprint, state, locked_until, expires_at)
33
+ VALUES ($1, $2, $3, 'in_progress',
34
+ now() + make_interval(secs => $4), now() + make_interval(secs => $5))
35
+ ON CONFLICT (scope, key) DO NOTHING
36
+ RETURNING 1
37
+ """
38
+
39
+ SELECT_EXISTING = """
40
+ SELECT fingerprint, state, response_status, response_headers, response_body,
41
+ GREATEST(1, CEIL(EXTRACT(EPOCH FROM (locked_until - now()))))::int AS retry_after,
42
+ locked_until < now() AS lock_expired
43
+ FROM idempotency_keys
44
+ WHERE scope = $1 AND key = $2
45
+ """
46
+
47
+ TAKE_OVER = """
48
+ UPDATE idempotency_keys
49
+ SET locked_until = now() + make_interval(secs => $3)
50
+ WHERE scope = $1 AND key = $2 AND state = 'in_progress' AND locked_until < now()
51
+ RETURNING 1
52
+ """
53
+
54
+ COMPLETE = """
55
+ UPDATE idempotency_keys
56
+ SET state = 'completed', response_status = $3,
57
+ response_headers = $4::jsonb, response_body = $5
58
+ WHERE scope = $1 AND key = $2
59
+ """
60
+
61
+ RELEASE = """
62
+ DELETE FROM idempotency_keys WHERE scope = $1 AND key = $2 AND state = 'in_progress'
63
+ """
64
+ PURGE_EXPIRED = """
65
+ DELETE FROM idempotency_keys WHERE expires_at < now()
66
+ """
67
+
68
+
69
+ class PostgresStorage:
70
+ def __init__(self, pool: asyncpg.Pool) -> None:
71
+ self._pool = pool
72
+
73
+ async def create_schema(self) -> None:
74
+ async with self._pool.acquire() as conn:
75
+ await conn.execute(SCHEMA)
76
+
77
+ async def claim(
78
+ self,
79
+ scope: str,
80
+ key: str,
81
+ fingerprint: bytes,
82
+ lock_seconds: int,
83
+ ttl_seconds: int,
84
+ ) -> ClaimResult:
85
+ async with self._pool.acquire() as conn:
86
+ # Цикл нужен на случай, если строку удалили между INSERT и SELECT.
87
+ for _ in range(3):
88
+ await conn.execute(DELETE_EXPIRED, scope, key)
89
+
90
+ inserted = await conn.fetchval(
91
+ INSERT_NEW, scope, key, fingerprint, float(lock_seconds), float(ttl_seconds)
92
+ )
93
+ if inserted:
94
+ return ClaimResult(ClaimStatus.ACQUIRED)
95
+
96
+ row = await conn.fetchrow(SELECT_EXISTING, scope, key)
97
+ if row is None:
98
+ continue
99
+
100
+ if bytes(row["fingerprint"]) != fingerprint:
101
+ return ClaimResult(ClaimStatus.MISMATCH)
102
+
103
+ if row["state"] == "completed":
104
+ headers = [(str(k), str(v)) for k, v in json.loads(row["response_headers"])]
105
+ response = StoredResponse(
106
+ status=row["response_status"],
107
+ headers=headers,
108
+ body=bytes(row["response_body"]),
109
+ )
110
+ return ClaimResult(ClaimStatus.REPLAY, response=response)
111
+
112
+ if not row["lock_expired"]:
113
+ return ClaimResult(ClaimStatus.IN_PROGRESS, retry_after=row["retry_after"])
114
+
115
+ # Блокировка просрочена (процесс, вероятно, упал): пробуем перехватить.
116
+ taken = await conn.fetchval(TAKE_OVER, scope, key, float(lock_seconds))
117
+ if taken:
118
+ return ClaimResult(ClaimStatus.ACQUIRED)
119
+ # Кто-то перехватил раньше нас: повторяем цикл.
120
+ raise RuntimeError("could not claim idempotency key")
121
+
122
+ async def complete(self, scope: str, key: str, response: StoredResponse) -> None:
123
+ headers_json = json.dumps(response.headers)
124
+ async with self._pool.acquire() as conn:
125
+ await conn.execute(COMPLETE, scope, key, response.status, headers_json, response.body)
126
+
127
+ async def release(self, scope: str, key: str) -> None:
128
+ async with self._pool.acquire() as conn:
129
+ await conn.execute(RELEASE, scope, key)
130
+
131
+ async def purge_expired(self) -> int:
132
+ """Delete all expired keys. Returns the number of deleted rows."""
133
+ async with self._pool.acquire() as conn:
134
+ status: str = await conn.execute(PURGE_EXPIRED)
135
+ # asyncpg возвращает строку вида "DELETE 3"
136
+ return int(status.split()[-1])
File without changes
@@ -0,0 +1,113 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from idempotency_asgi.storage import ClaimResult, ClaimStatus, StoredResponse
7
+
8
+ # KEYS[1] = ключ хэша
9
+ # ARGV[1] = fingerprint (hex), ARGV[2] = lock_seconds, ARGV[3] = ttl_seconds
10
+ # Возвращает {код, retry_after}:
11
+ # 1 = ACQUIRED, 2 = REPLAY, 3 = IN_PROGRESS, 4 = MISMATCH
12
+ CLAIM_LUA = """
13
+ local t = redis.call('TIME')
14
+ local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
15
+ local lock = tonumber(ARGV[2])
16
+ local ttl = tonumber(ARGV[3])
17
+
18
+ if redis.call('EXISTS', KEYS[1]) == 0 then
19
+ redis.call('HSET', KEYS[1], 'fp', ARGV[1], 'state', 'in_progress',
20
+ 'locked_until', tostring(now + lock))
21
+ redis.call('EXPIRE', KEYS[1], ttl)
22
+ return {1, 0}
23
+ end
24
+
25
+ local fp = redis.call('HGET', KEYS[1], 'fp')
26
+ if fp ~= ARGV[1] then
27
+ return {4, 0}
28
+ end
29
+
30
+ local state = redis.call('HGET', KEYS[1], 'state')
31
+ if state == 'completed' then
32
+ return {2, 0}
33
+ end
34
+
35
+ local locked_until = tonumber(redis.call('HGET', KEYS[1], 'locked_until'))
36
+ if locked_until > now then
37
+ return {3, math.max(1, math.ceil(locked_until - now))}
38
+ end
39
+
40
+ redis.call('HSET', KEYS[1], 'locked_until', tostring(now + lock))
41
+ return {1, 0}
42
+ """
43
+
44
+ COMPLETE_LUA = """
45
+ if redis.call('EXISTS', KEYS[1]) == 0 then
46
+ return 0
47
+ end
48
+ redis.call('HSET', KEYS[1], 'state', 'completed', 'response', ARGV[1])
49
+ return 1
50
+ """
51
+
52
+ RELEASE_LUA = """
53
+ if redis.call('HGET', KEYS[1], 'state') == 'in_progress' then
54
+ return redis.call('DEL', KEYS[1])
55
+ end
56
+ return 0
57
+ """
58
+
59
+
60
+ class RedisStorage:
61
+ def __init__(self, client: Any, prefix: str = "idem") -> None:
62
+ self._r = client
63
+ self._prefix = prefix
64
+ self._claim = client.register_script(CLAIM_LUA)
65
+ self._complete = client.register_script(COMPLETE_LUA)
66
+ self._release = client.register_script(RELEASE_LUA)
67
+
68
+ def _key(self, scope: str, key: str) -> str:
69
+ # Длина scope в префиксе исключает путаницу между ("a:b", "c") и ("a", "b:c").
70
+ return f"{self._prefix}:{len(scope)}:{scope}:{key}"
71
+
72
+ async def claim(
73
+ self,
74
+ scope: str,
75
+ key: str,
76
+ fingerprint: bytes,
77
+ lock_seconds: int,
78
+ ttl_seconds: int,
79
+ ) -> ClaimResult:
80
+ code, retry_after = await self._claim(
81
+ keys=[self._key(scope, key)],
82
+ args=[fingerprint.hex(), lock_seconds, ttl_seconds],
83
+ )
84
+ if code == 1:
85
+ return ClaimResult(ClaimStatus.ACQUIRED)
86
+ if code == 2:
87
+ raw = await self._r.hget(self._key(scope, key), "response")
88
+ if raw is None:
89
+ # Запись исчезла (TTL) между скриптом и чтением: пробуем заново.
90
+ return await self.claim(scope, key, fingerprint, lock_seconds, ttl_seconds)
91
+ data = json.loads(raw)
92
+ response = StoredResponse(
93
+ status=data["status"],
94
+ headers=[(k, v) for k, v in data["headers"]],
95
+ body=bytes.fromhex(data["body"]),
96
+ )
97
+ return ClaimResult(ClaimStatus.REPLAY, response=response)
98
+ if code == 3:
99
+ return ClaimResult(ClaimStatus.IN_PROGRESS, retry_after=int(retry_after))
100
+ return ClaimResult(ClaimStatus.MISMATCH)
101
+
102
+ async def complete(self, scope: str, key: str, response: StoredResponse) -> None:
103
+ payload = json.dumps(
104
+ {
105
+ "status": response.status,
106
+ "headers": response.headers,
107
+ "body": response.body.hex(),
108
+ }
109
+ )
110
+ await self._complete(keys=[self._key(scope, key)], args=[payload])
111
+
112
+ async def release(self, scope: str, key: str) -> None:
113
+ await self._release(keys=[self._key(scope, key)])
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from enum import Enum
5
+ from typing import Protocol
6
+
7
+
8
+ class ClaimStatus(Enum):
9
+ ACQUIRED = "acquired" # ключ новый (или перехвачен), можно выполнять обработчик
10
+ REPLAY = "replay" # запрос уже выполнен, есть сохранённый ответ
11
+ IN_PROGRESS = "in_progress" # another request with this key is still running
12
+ MISMATCH = "mismatch" # same key, but a different request
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class StoredResponse:
17
+ status: int
18
+ headers: list[tuple[str, str]]
19
+ body: bytes
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class ClaimResult:
24
+ status: ClaimStatus
25
+ response: StoredResponse | None = None # заполнено при REPLAY
26
+ retry_after: int | None = None # заполнено при IN_PROGRESS (секунды)
27
+
28
+
29
+ class Storage(Protocol):
30
+ async def claim(
31
+ self,
32
+ scope: str,
33
+ key: str,
34
+ fingerprint: bytes,
35
+ lock_seconds: int,
36
+ ttl_seconds: int,
37
+ ) -> ClaimResult: ...
38
+
39
+ async def complete(self, scope: str, key: str, response: StoredResponse) -> None: ...
40
+
41
+ async def release(self, scope: str, key: str) -> None: ...
@@ -0,0 +1,206 @@
1
+ Metadata-Version: 2.5
2
+ Name: idempotency-asgi
3
+ Version: 0.1.0
4
+ Summary: Idempotency-Key middleware for ASGI apps (FastAPI/Starlette)
5
+ Project-URL: Repository, https://github.com/adsetsuko0/idempotency-asgi
6
+ Project-URL: Issues, https://github.com/adsetsuko0/idempotency-asgi/issues
7
+ Author: Anna Ermak
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: asgi,fastapi,idempotency,middleware,starlette
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: FastAPI
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Provides-Extra: postgres
23
+ Requires-Dist: asyncpg>=0.29; extra == 'postgres'
24
+ Provides-Extra: redis
25
+ Requires-Dist: redis>=5.0; extra == 'redis'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # idempotency-asgi
29
+
30
+ [![CI](https://github.com/adsetsuko0/idempotency-asgi/actions/workflows/ci.yml/badge.svg)](https://github.com/adsetsuko0/idempotency-asgi/actions/workflows/ci.yml)
31
+ ![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)
32
+ ![License](https://img.shields.io/badge/license-MIT-green)
33
+
34
+ `Idempotency-Key` middleware for ASGI apps (FastAPI, Starlette). It makes `POST` and `PATCH` requests safe to retry: the handler runs once per key, and every retry gets the stored response.
35
+
36
+ - Pure ASGI, no dependency on FastAPI or Starlette in the core
37
+ - Two interchangeable backends: **PostgreSQL** and **Redis** (atomic Lua scripts)
38
+ - Handles concurrent duplicates, changed request bodies, and crashed processes
39
+ - Fully typed (`mypy --strict`), tested on Python 3.11, 3.12 and 3.13
40
+
41
+ ## The problem
42
+
43
+ A client sends `POST /payments`, the network hangs, and the client retries. Without protection the server charges the customer twice.
44
+
45
+ With this middleware the client attaches a unique `Idempotency-Key` header. The first request runs normally and its response is stored. Any retry with the same key gets the stored response back, and the handler is not called again.
46
+
47
+ ## Quickstart
48
+
49
+ ```bash
50
+ pip install "idempotency-asgi[redis]" # or [postgres]
51
+ ```
52
+
53
+ ```python
54
+ import redis.asyncio as aioredis
55
+ from fastapi import FastAPI
56
+ from idempotency_asgi import IdempotencyMiddleware
57
+ from idempotency_asgi.redis_storage import RedisStorage
58
+
59
+ app = FastAPI()
60
+ app.add_middleware(
61
+ IdempotencyMiddleware, storage=RedisStorage(aioredis.from_url("redis://localhost:6379/0"))
62
+ )
63
+ ```
64
+
65
+ Try it:
66
+
67
+ ```bash
68
+ curl -X POST http://localhost:8000/payments \
69
+ -H "Idempotency-Key: pay-1" -H "Content-Type: application/json" \
70
+ -d '{"amount": 100}'
71
+ # repeat the same command: same response, plus "Idempotency-Replayed: true"
72
+ ```
73
+
74
+ ### PostgreSQL backend
75
+
76
+ The connection pool must be created in an async context, so create it at startup, call `create_schema()` once, and (optionally) run the background cleanup of expired keys:
77
+
78
+ ```python
79
+ pool = await asyncpg.create_pool("postgresql://user:pass@host/db")
80
+ storage = PostgresStorage(pool)
81
+ await storage.create_schema()
82
+ async with cleanup_task(storage, interval_seconds=300):
83
+ ...
84
+ ```
85
+
86
+ A complete working example, including a lazy storage wrapper (because middleware is built before the pool exists), is in [`examples/demo_app/main.py`](examples/demo_app/main.py). Run the databases with `docker compose up -d`.
87
+
88
+ ### Configuration
89
+
90
+ | Parameter | Default | Meaning |
91
+ |---|---|---|
92
+ | `storage` | required | `PostgresStorage` or `RedisStorage` (any object implementing the `Storage` protocol) |
93
+ | `scope_getter` | returns `"global"` | Function `scope -> str` that decides who owns a key (user, tenant). Keys are unique per `(scope, key)` |
94
+ | `lock_seconds` | 30 | How long a running request holds its key |
95
+ | `ttl_seconds` | 86400 | How long a stored response is kept (24 h) |
96
+ | `max_body_bytes` | 1 000 000 | Larger request bodies get `413` |
97
+ | `max_response_bytes` | 1 000 000 | Larger responses are returned but not stored |
98
+ | `require_key` | `False` | If `True`, `POST`/`PATCH` without the header get `400` |
99
+
100
+ ## Behavior
101
+
102
+ Only `POST` and `PATCH` requests with an `Idempotency-Key` header are handled. Everything else passes through untouched.
103
+
104
+ | Situation | Result |
105
+ |---|---|
106
+ | New key | Handler runs, response is stored |
107
+ | Same key, same request, already completed | Stored response is returned with `Idempotency-Replayed: true`, handler is not called |
108
+ | Same key, request still running | `409 Conflict` with `Retry-After` |
109
+ | Same key, different request (method, path, query or body) | `422 Unprocessable Entity` |
110
+ | Handler returns `5xx` or raises | Nothing is stored, the key is released, the client may retry |
111
+ | Lock expired (process crashed) | Next request takes over the key and runs the handler |
112
+ | Streaming or oversized response | Delivered to the client, not stored, key is released |
113
+ | Header missing and `require_key=True` | `400 Bad Request` |
114
+ | Request body above `max_body_bytes` | `413 Payload Too Large` |
115
+
116
+ ```mermaid
117
+ stateDiagram-v2
118
+ [*] --> in_progress: claim (new key)
119
+ in_progress --> completed: handler finished, response stored
120
+ in_progress --> [*]: handler failed (5xx / exception), key released
121
+ in_progress --> in_progress: lock expired, another request takes over
122
+ completed --> [*]: TTL expired
123
+ ```
124
+
125
+ The request fingerprint is a SHA-256 of the method, path, sorted query parameters and body. Sensitive headers (`authorization`, `cookie`, `set-cookie`, `proxy-authenticate`) are never written to the storage. The client still receives them in the first response.
126
+
127
+ ## What breaks and how I verified it
128
+
129
+ | Failure | How it is handled | How it is tested |
130
+ |---|---|---|
131
+ | 50 identical requests at the same moment | Atomic claim: exactly one wins, the rest get `409` | `test_fifty_parallel_requests_run_handler_once` (middleware), `test_concurrent_claims_only_one_wins` (storage) |
132
+ | Client retries with a different body | `422`, handler not called | `test_different_body_returns_422` |
133
+ | Handler fails with `5xx` | Key is released so the retry can succeed | `test_5xx_releases_key_so_client_can_retry` |
134
+ | Process dies mid-request | Lock expires, next request takes the key over | `test_expired_lock_is_taken_over_after_crash` |
135
+ | Process is killed with no cleanup | Same recovery, with a real server process killed | `test_key_recovers_after_process_is_killed` (chaos test) |
136
+ | Two users pick the same key | Keys are isolated by scope | `test_scopes_are_isolated` |
137
+ | Streaming or huge response | Not stored, not replayed from storage | `test_streaming_response_is_not_stored`, `test_oversized_response_is_not_stored` |
138
+ | Secrets in stored responses | Sensitive headers are dropped | `test_sensitive_headers_are_not_replayed` |
139
+ | Unbounded table growth | Expired keys are purged in the background (Postgres), `EXPIRE` (Redis) | `tests/test_cleanup.py` |
140
+ | Unexpected sequences of operations | Random sequences are compared with a reference model | Hypothesis state machine (40 examples, 30 steps each) |
141
+
142
+ The same storage and middleware tests run against **both** backends through a parametrized pytest fixture, so the `Storage` protocol is exercised for real. The full suite has 57 tests and runs in CI against real PostgreSQL 16 and Redis 7 service containers.
143
+
144
+ ```bash
145
+ docker compose up -d
146
+ uv sync
147
+ uv run pytest
148
+ ```
149
+
150
+ ## Design decisions
151
+
152
+ - **Pure ASGI instead of `BaseHTTPMiddleware`.** `BaseHTTPMiddleware` is awkward with request bodies and streaming. A plain ASGI middleware gives full control over what is read and sent.
153
+ - **Atomicity comes from the database.** A "check, then write" sequence breaks under concurrent requests. PostgreSQL uses `INSERT ... ON CONFLICT (scope, key) DO NOTHING`; Redis uses a Lua script, which runs as one uninterruptible unit.
154
+ - **`locked_until` instead of a permanent lock.** If a process dies, its key must not stay busy forever. After the lock expires, another request takes the key over atomically (`UPDATE ... WHERE locked_until < now()` in Postgres, the same check inside the Lua script in Redis).
155
+ - **Server-side time.** Lock expiry and TTL are computed with the database clock (`now()` in Postgres, `TIME` in Redis), so several app servers cannot disagree about time.
156
+ - **Failures are not cached.** A `5xx` response is not stored, so a temporary error does not become permanent for that key. The trade-off: a handler that failed after a side effect may run again.
157
+ - **Last response message is held until it is stored.** The client receives the final chunk only after the response is saved, so an immediate retry does not hit a false `409`.
158
+ - **Core has no dependencies.** Backends are optional extras (`[postgres]`, `[redis]`), and the `Storage` protocol allows adding more.
159
+
160
+ ## Benchmarks
161
+
162
+ Overhead for a request with a **new key** (the most expensive path: `claim`, handler, `complete`). 2000 requests per configuration, 20 concurrent, three runs, median shown.
163
+
164
+ | Configuration | req/s | p50, ms | p95, ms | p99, ms |
165
+ |---|---|---|---|---|
166
+ | No middleware | 783 | 1.05 | 2.18 | 3.04 |
167
+ | Middleware + PostgreSQL | 443 | 39.04 | 65.82 | 78.35 |
168
+ | Middleware + Redis | 542 | 29.72 | 52.92 | 61.29 |
169
+
170
+ Redis is roughly 25% faster than PostgreSQL at p50 and about 20% faster at p99 in this setup.
171
+
172
+ Caveats:
173
+ - Local measurement: app, PostgreSQL and Redis run on one Windows machine, with the databases in Docker. A Linux server will likely show different numbers.
174
+ - Requests go through `httpx.ASGITransport`, with no network and no uvicorn, so this measures the library and storage cost only.
175
+ - Each request makes two storage calls and 20 requests compete for connections, so latency includes queueing. Throughput is the more meaningful number.
176
+ - Run-to-run spread is noticeable (PostgreSQL p50 ranged from 39 to 46 ms).
177
+ - Replay latency (retries of a completed key) was not measured.
178
+
179
+ Reproduce: `uv run python benchmarks/bench.py`
180
+
181
+ ## Limitations
182
+
183
+ - If a handler runs longer than `lock_seconds`, another request can take over the key and run the handler a second time. Set `lock_seconds` above your slowest handler.
184
+ - The middleware sees only HTTP. Side effects such as sending an email or calling an external API are not made idempotent by it. Use the same idempotency key downstream, or commit the key in the same database transaction as your business data.
185
+ - Streaming and oversized responses are not stored, so retries of those requests are **not** protected.
186
+ - If storing the response fails after the handler succeeded, the client still gets the response and the key is released, so a retry would run the handler again.
187
+ - The default scope is `"global"`: all clients share one key space. In real applications pass `scope_getter` (for example, the authenticated user id).
188
+ - Redis durability depends on your Redis persistence settings. For payments-grade guarantees prefer PostgreSQL.
189
+ - The Hypothesis state machine and the chaos test run against the PostgreSQL backend only.
190
+
191
+ ## Development
192
+
193
+ ```bash
194
+ uv sync # create the environment
195
+ docker compose up -d # PostgreSQL 16 and Redis 7
196
+ uv run pytest # tests
197
+ uv run ruff check . # lint
198
+ uv run ruff format . # format
199
+ uv run mypy # strict type checking
200
+ ```
201
+
202
+ Pre-commit hooks (ruff, ruff format, mypy) run on every commit. The design notes are in [`docs/design.md`](docs/design.md).
203
+
204
+ ## License
205
+
206
+ MIT
@@ -0,0 +1,12 @@
1
+ idempotency_asgi/__init__.py,sha256=qmWE5sFhK1JRnKmnvLPzKppR3jusM_H4dBy3-DfTu3Y,121
2
+ idempotency_asgi/_types.py,sha256=eis2ArXXcKK_mVZx_KYlsP6Gq7EyGo-ZKg_dFISSoSc,303
3
+ idempotency_asgi/cleanup.py,sha256=1PV7fod2gIgJ-b_wzNKbvaTD2cX497qqyKo1VYkR4zI,1283
4
+ idempotency_asgi/middleware.py,sha256=C7jE5nq9NoZeaa4SkxrkN61978V76lIcKBd6PKYa-bs,7983
5
+ idempotency_asgi/postgres.py,sha256=caOlpnuua7StNVACJZd7HImg-ip_ugVqIsRXUwCBmlM,5041
6
+ idempotency_asgi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ idempotency_asgi/redis_storage.py,sha256=TNwjHByOaNpWRe6ocm1-27jKOhriOzGbiwEF9c2COg4,3756
8
+ idempotency_asgi/storage.py,sha256=b7wdYLj2hO7ty7ey7ixENRnq3mdbD6qsuUz-COy3yLo,1271
9
+ idempotency_asgi-0.1.0.dist-info/METADATA,sha256=FbFY6ncc9EAKnfciTpnV_9cXzddPhs26Ts5zOpxK-Tg,11503
10
+ idempotency_asgi-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ idempotency_asgi-0.1.0.dist-info/licenses/LICENSE,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ idempotency_asgi-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
File without changes