mirror of
https://github.com/exo-explore/exo.git
synced 2026-04-26 16:58:32 -04:00
33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
from hashlib import sha3_224 as hasher
|
|
from typing import Sequence
|
|
from uuid import UUID
|
|
|
|
from shared.types.events.common import EventCategory, EventId, IdemKeyGenerator, State
|
|
|
|
|
|
def get_idem_tag_generator[EventCategoryT: EventCategory](
|
|
base: str,
|
|
) -> IdemKeyGenerator[EventCategoryT]:
|
|
"""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[EventCategoryT], num_keys: int) -> Sequence[EventId]:
|
|
def recurse(n: int, last: bytes) -> Sequence[EventId]:
|
|
if n == 0:
|
|
return []
|
|
next_hash = hasher(last).digest()
|
|
return (
|
|
EventId(UUID(bytes=next_hash, version=4)),
|
|
*recurse(n - 1, next_hash),
|
|
)
|
|
|
|
initial_bytes = state.last_event_applied_idx.to_bytes(
|
|
8, byteorder="big", signed=False
|
|
)
|
|
return recurse(num_keys, initial_bytes)
|
|
|
|
return get_idem_keys
|