Coverage for src/copytrading_engine/shared/route_keys.py: 100%

17 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""Which configured route a source message follows; parsing and delivery must pick the same one.""" 

2 

3import hashlib 

4from collections.abc import Mapping 

5from dataclasses import dataclass 

6 

7AMBIGUOUS_SOURCE_PROFILE = "ambiguous_source_profile" 

8 

9 

10def guru_for_channel(source: str, channel_id: str) -> str: 

11 """A guru's ID. Each channel has one guru, so the channel names them: setting up again, or 

12 importing the same setup, gives the guru the same ID and their history stays theirs.""" 

13 return "guru-" + hashlib.sha256(f"{source}:{channel_id}".encode()).hexdigest()[:8] 

14 

15 

16def route_key(source: str, channel_id: str, author_id: str | None) -> str: 

17 """A route is bound to one author, or to every author in the channel (`*`).""" 

18 return f"{source}:{channel_id}:{author_id or '*'}" 

19 

20 

21@dataclass(frozen=True, slots=True) 

22class RouteChoice[T]: 

23 route: T | None 

24 error: str | None = None 

25 

26 

27def choose_route[T]( 

28 routes: Mapping[str, T], source: str, channel_id: str, author_id: str | None 

29) -> RouteChoice[T]: 

30 """The author's own route, else the channel's; configuring both for one author is ambiguous.""" 

31 exact = routes.get(route_key(source, channel_id, author_id)) if author_id is not None else None 

32 wildcard = routes.get(route_key(source, channel_id, None)) 

33 if exact is not None and wildcard is not None: 

34 return RouteChoice(None, AMBIGUOUS_SOURCE_PROFILE) 

35 return RouteChoice(exact if exact is not None else wildcard)