Files
exo/master/idempotency.py
2025-06-29 19:44:58 +01:00

27 lines
1.0 KiB
Python

from hashlib import sha3_224 as hasher
from typing import Sequence, TypeVar
from shared.types.event_sourcing import EventId, EventTypes, IdemKeyGenerator, State
EventTypeT = TypeVar("EventTypeT", bound=EventTypes)
def get_idem_tag_generator(base: str) -> IdemKeyGenerator[EventTypeT]:
"""Generates idempotency keys for events.
The keys are generated by hashing the state sequence number against a base string.
You can pick any base string, **so long as it's not used in any other function that generates idempotency keys**.
"""
def get_idem_keys(state: State[EventTypeT], num_keys: int) -> Sequence[EventId]:
def recurse(n: int, last: bytes) -> Sequence[EventId]:
if n == 0:
return []
next_hash = hasher(last).digest()
return (EventId(next_hash.hex()), *recurse(n - 1, next_hash))
initial_bytes = state.sequence_number.to_bytes(8, byteorder="big", signed=False)
return recurse(num_keys, initial_bytes)
return get_idem_keys