Idempotency
rn_forge.web.idempotency
Idempotency store protocols, request hashing, and in-memory test doubles.
Stores must claim keys atomically. Reusing a key with a different request hash is an error (422); a claim still in flight is a distinct error (409); a completed key replays its stored response.
IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key'
module-attribute
The request header carrying the key (draft-ietf-httpapi-idempotency-key-header).
SAFE_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'})
module-attribute
Methods :func:run_idempotent bypasses the store for.
AsyncIdempotencyStore
Bases: Protocol
The async counterpart of :class:IdempotencyStore, with identical semantics.
complete(*, scope, key, status, response_body)
async
See :meth:IdempotencyStore.complete.
record_or_replay(*, scope, key, request_body)
async
See :meth:IdempotencyStore.record_or_replay.
IdempotencyStore
Bases: Protocol
The synchronous idempotency-key contract.
The claim made by :meth:record_or_replay must be atomic.
complete(*, scope, key, status, response_body)
Store the response produced for a claimed key.
record_or_replay(*, scope, key, request_body)
Claim key within scope, or return the response already stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scope
|
str
|
An opaque namespace. A tenant-scoped consumer passes the tenant id; an endpoint-scoped one passes the route name. Keys in different scopes never collide. |
required |
key
|
str
|
The client's |
required |
request_body
|
Any
|
The request body, hashed for reuse detection. |
required |
Returns:
| Type | Description |
|---|---|
StoredResponse | None
|
|
StoredResponse | None
|
meth: |
StoredResponse | None
|
this key has already completed. |
Raises:
| Type | Description |
|---|---|
IdempotencyKeyReuse
|
key was seen with a different body. |
IdempotencyKeyInFlight
|
key was claimed and its original request has not completed. |
InMemoryAsyncIdempotencyStore()
An async wrapper around the in-memory test store.
complete(*, scope, key, status, response_body)
async
See :meth:AsyncIdempotencyStore.complete.
record_or_replay(*, scope, key, request_body)
async
See :meth:AsyncIdempotencyStore.record_or_replay.
InMemoryIdempotencyStore()
A dict-backed :class:IdempotencyStore for tests.
It holds everything forever and is not shared between processes, so it is a test double, not a production store.
complete(*, scope, key, status, response_body)
See :meth:IdempotencyStore.complete.
record_or_replay(*, scope, key, request_body)
See :meth:IdempotencyStore.record_or_replay.
StoredResponse(status, body, replayed=False)
dataclass
Bases: DataclassMixin
A response held against an idempotency key.
__repr__()
Return an unambiguous ClassName(field=value, ...) representation.
Excluded fields (metadata={"exclude": True}) are omitted. Falls
back to :func:object.__repr__ when the class is not a dataclass.
Returns:
| Type | Description |
|---|---|
str
|
A string of the form |
__str__()
Return a JSON string representation of this instance.
Equivalent to calling :meth:to_json. Excluded fields are omitted.
Returns:
| Type | Description |
|---|---|
str
|
A compact JSON string (no indentation). |
as_dict(*, exclude_hidden=True)
Convert this dataclass instance to a plain dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_hidden
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict mapping field names to their current values. Nested |
dict[str, Any]
|
dataclasses are recursively converted, respecting |
dict[str, Any]
|
metadata at every level. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the subclass was not decorated with
|
from_dict(data)
classmethod
Create an instance from a dict, recursively rebuilding nested dataclasses.
Only keys that match declared dataclass field names are passed to the
constructor. This makes from_dict tolerant of extra data (e.g.
when loading from a config file that has fields added in a newer
schema version). Nested dataclass-typed fields are reconstructed
recursively for common container annotations, via :mod:dacite.
Note a nested dataclass field's own overridden from_dict (if any)
is not called — dacite structures nested dataclasses itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
A dict whose keys correspond to dataclass field names.
Unrecognised keys are silently ignored, or rejected when the
class's |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance of this class populated with matching field values. |
Raises:
| Type | Description |
|---|---|
AppException
|
A value does not match its field's declared type, a
required field is absent, or an enum-typed field names a member
the enum does not define. Under |
TypeError
|
If the subclass was not decorated with
|
from_json(text)
classmethod
Create an instance from a JSON string.
Delegates to :meth:from_dict after parsing, so unknown keys are
ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A JSON string representing a dict of field values. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance populated from the parsed JSON. |
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If text is not valid JSON. |
from_yaml(text)
classmethod
Create an instance from a YAML string.
Delegates to :meth:from_dict after parsing, so unknown keys are
ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A YAML string representing a mapping of field values. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance populated from the parsed YAML. |
Raises:
| Type | Description |
|---|---|
YAMLError
|
If text is not valid YAML. |
to_json(*, indent=None, **kwargs)
Serialise this instance to a JSON string.
Fields excluded via metadata={"exclude": True} are omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indent
|
str | int | None
|
Indentation level passed to :func: |
None
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to
:func: |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A JSON string representation of this instance. |
to_yaml(**kwargs)
Serialise this instance to a YAML string.
Fields excluded via metadata={"exclude": True} are omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Additional keyword arguments forwarded to
:meth: |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A YAML string representation of this instance. |
check_idempotency_key(value, *, header=IDEMPOTENCY_KEY_HEADER)
Return value, the request's idempotency key, raising when it is absent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str | None
|
The header's value, or |
required |
header
|
str
|
The header's name, for the error detail. |
IDEMPOTENCY_KEY_HEADER
|
Raises:
| Type | Description |
|---|---|
IdempotencyKeyRequired
|
value is |
request_hash(body)
Return a SHA-256 over a canonical JSON encoding of body.
Canonical means sort_keys=True with no whitespace, so two bodies that
differ only in key order or formatting hash identically — otherwise a
client library that reorders JSON keys turns every retry into a 409.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
body
|
Any
|
Any JSON-serializable value. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The hash as a lowercase hex digest. |
run_idempotent(store, *, scope, key, method, body, execute, header=IDEMPOTENCY_KEY_HEADER)
Run execute under the idempotency-key protocol.
A safe method (:data:SAFE_METHODS) bypasses the store entirely and just
runs execute. An unsafe method requires key, claims it, replays a
completed key's stored response, and stores what execute returns on
first sight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
IdempotencyStore
|
The idempotency store. |
required |
scope
|
str
|
An opaque namespace for the key — see
:meth: |
required |
key
|
str | None
|
The client's |
required |
method
|
str
|
The request's HTTP method, any case. |
required |
body
|
Any
|
The request body, hashed for reuse detection. |
required |
execute
|
Callable[[], tuple[int, Mapping[str, Any]]]
|
Runs the handler, returning |
required |
header
|
str
|
The header's name, for :exc: |
IDEMPOTENCY_KEY_HEADER
|
Returns:
| Type | Description |
|---|---|
StoredResponse
|
The response to send. |
StoredResponse
|
replay. |
Raises:
| Type | Description |
|---|---|
IdempotencyKeyRequired
|
An unsafe method and key is absent (400). |
IdempotencyKeyReuse
|
key was seen with a different body (422). |
IdempotencyKeyInFlight
|
key is claimed and still in flight (409). |
run_idempotent_async(store, *, scope, key, method, body, execute, header=IDEMPOTENCY_KEY_HEADER)
async
See :func:run_idempotent; identical semantics over the async store and execute.