Skip to content

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 Idempotency-Key.

required
request_body Any

The request body, hashed for reuse detection.

required

Returns:

Type Description
StoredResponse | None

None on first sight — the caller executes and then calls

StoredResponse | None

meth:complete. The stored response (with replayed=True) when

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 ClassName(field1=value1, field2=value2).

__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 (default), fields decorated with metadata={"exclude": True} are omitted from the result, recursively throughout nested dataclasses. Pass False to include every field.

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 exclude

dict[str, Any]

metadata at every level.

Raises:

Type Description
TypeError

If the subclass was not decorated with @dataclasses.dataclass.

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 __dacite_config__ sets strict.

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 strict, also a key that names no field, at any nesting level; the message lists every such key by its dotted path (repository.archtype).

TypeError

If the subclass was not decorated with @dataclasses.dataclass.

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:json.dumps. None produces compact output.

None
**kwargs Any

Additional keyword arguments forwarded to :func:json.dumps.

{}

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:~rn_forge.commons.fs.documents.YamlUtils.serialize (e.g. sort_keys, default_flow_style).

{}

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 None when absent.

required
header str

The header's name, for the error detail.

IDEMPOTENCY_KEY_HEADER

Raises:

Type Description
IdempotencyKeyRequired

value is None or empty (400).

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. None is a valid body and hashes like any other.

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:IdempotencyStore.record_or_replay.

required
key str | None

The client's Idempotency-Key header value, or None.

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 (status, response_body).

required
header str

The header's name, for :exc:IdempotencyKeyRequired's detail.

IDEMPOTENCY_KEY_HEADER

Returns:

Type Description
StoredResponse

The response to send. replayed is True only for a stored

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.