mirror of
https://github.com/exo-explore/exo.git
synced 2026-06-26 14:45:50 -04:00
27 lines
1.0 KiB
Python
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
|