Coverage for src/copytrading_engine/control/policy.py: 94%

84 statements  

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

1"""Which control operations may run, which need the owner, and how fast callers may ask.""" 

2 

3import datetime as dt 

4from collections import deque 

5from dataclasses import dataclass 

6from typing import Final, Literal, assert_never 

7 

8from copytrading_engine.control.wire import ErrorCode, Operation 

9 

10type Tier = Literal["read", "safer", "approval"] 

11type AccessLevel = Literal["read_pause", "propose"] 

12 

13RATE_LIMIT: Final = 30 

14RATE_WINDOW: Final = dt.timedelta(seconds=10) 

15 

16 

17def tier(operation: Operation) -> Tier: 

18 """Classify every operation; adding one without a tier fails type checking.""" 

19 match operation: 

20 case ( 

21 "get_status" 

22 | "list_accounts" 

23 | "list_activity" 

24 | "list_account_events" 

25 | "list_manual_commands" 

26 | "get_manual_command" 

27 | "preview_manual_order" 

28 | "list_proposals" 

29 | "get_proposal" 

30 | "get_setup" 

31 ): 

32 return "read" 

33 case "pause_processing" | "pause_account": 

34 return "safer" 

35 case ( 35 ↛ 51line 35 didn't jump to line 51 because the pattern on line 35 always matched

36 "propose_resume_account" 

37 | "propose_recovery_preference" 

38 | "propose_manual_order" 

39 | "propose_set_account_limits" 

40 | "propose_start_processing" 

41 | "edit_setup_discord" 

42 | "edit_setup_model" 

43 | "edit_setup_account" 

44 | "edit_setup_guru" 

45 | "edit_setup_alerts" 

46 | "import_setup" 

47 | "apply_setup" 

48 | "discard_setup" 

49 ): 

50 return "approval" 

51 case _: 

52 assert_never(operation) 

53 

54 

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

56class Run: 

57 """Perform the operation now.""" 

58 

59 

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

61class Propose: 

62 """Record a proposal; only the owner's approval performs it.""" 

63 

64 

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

66class Refuse: 

67 code: ErrorCode 

68 

69 

70type Decision = Run | Propose | Refuse 

71 

72 

73# Setup changes need the propose level like every approval-tier operation, but the owner 

74# granted that level for them: an edit only changes the unsaved draft, and applying a paper-only 

75# setup runs Start Copying's own checks. Anything that touches a live account is a proposal. 

76SETUP_CHANGES: Final[frozenset[Operation]] = frozenset( 

77 { 

78 "edit_setup_discord", 

79 "edit_setup_model", 

80 "edit_setup_account", 

81 "edit_setup_guru", 

82 "edit_setup_alerts", 

83 "import_setup", 

84 "apply_setup", 

85 "discard_setup", 

86 } 

87) 

88 

89 

90def decide( 

91 operation: Operation, 

92 access: AccessLevel, 

93 *, 

94 unlocked: bool, 

95 owner_needed: bool = True, 

96 setup_changes: bool = False, 

97) -> Decision: 

98 """Pausing is always allowed; everything else needs an unlocked app, and proposals need 

99 the owner to have granted the propose level. A setup change also needs the owner's separate 

100 "Allow setup changes from the command line" (`setup_changes`); one the owner need not see then 

101 runs, and `owner_needed` says whether it touches real money.""" 

102 kind = tier(operation) 

103 if kind == "safer": 

104 return Run() 

105 if not unlocked: 

106 return Refuse("locked") 

107 if kind == "read": 

108 return Run() 

109 if access != "propose": 

110 return Refuse("forbidden") 

111 if operation in SETUP_CHANGES and not setup_changes: 

112 return Refuse("forbidden") 

113 if operation in SETUP_CHANGES and not owner_needed: 

114 return Run() 

115 return Propose() 

116 

117 

118class RateWindow: 

119 """Admit at most `limit` requests in any trailing `window`.""" 

120 

121 def __init__(self, limit: int = RATE_LIMIT, window: dt.timedelta = RATE_WINDOW) -> None: 

122 if limit < 1: 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true

123 raise ValueError("A rate window must admit at least one request") 

124 self._limit = limit 

125 self._window = window 

126 self._admitted: deque[dt.datetime] = deque() 

127 

128 def admit(self, now: dt.datetime) -> bool: 

129 while self._admitted and now - self._admitted[0] >= self._window: 

130 self._admitted.popleft() 

131 if len(self._admitted) >= self._limit: 

132 return False 

133 self._admitted.append(now) 

134 return True 

135 

136 

137def describe_refusal(code: ErrorCode) -> str: 

138 """A message a person or agent can act on.""" 

139 match code: 

140 case "access_off": 

141 return "Agent access is turned off in CopyTrading." 

142 case "locked": 

143 return "Unlock CopyTrading first." 

144 case "forbidden": 

145 return "Agent access allows reading and pausing only; proposals are not enabled." 

146 case "invalid_request": 

147 return "The request is not valid." 

148 case "not_found": 

149 return "Nothing matches that identifier." 

150 case "unavailable": 

151 return "The engine cannot answer right now." 

152 case "busy": 

153 return "Too many requests; wait a few seconds." 

154 case "cooling_down": 

155 return "Proposals are paused after repeated rejections; try again later." 

156 case "proposal_limit": 

157 return "A proposal of this kind is already waiting for the owner." 

158 case "conflict": 

159 return "The proposal changed or is no longer waiting." 

160 case "expired": 

161 return "The proposal expired before the owner approved it." 

162 case "rejected": 162 ↛ 164line 162 didn't jump to line 164 because the pattern on line 162 always matched

163 return "The owner rejected the proposal." 

164 case _: 

165 assert_never(code)