Coverage for src/copytrading_engine/control/client.py: 82%

100 statements  

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

1"""Find the app's or the headless server's control socket and exchange one request line.""" 

2 

3import asyncio 

4import contextlib 

5import json 

6import os 

7import stat 

8import sys 

9from collections.abc import Mapping 

10from pathlib import Path 

11from typing import Final 

12from uuid import uuid4 

13 

14from pydantic import ValidationError 

15 

16from copytrading_engine.control import wire 

17 

18DEFAULT_TIMEOUT: Final = 30.0 

19MAX_RESPONSE_BYTES: Final = 8 * 1024 * 1024 

20 

21 

22class AppUnavailable(Exception): 

23 """Neither the app nor the server is running, or agent access is off.""" 

24 

25 

26class UnsafeSocket(Exception): 

27 """The socket path was not created by the owner's app, so it is never used.""" 

28 

29 

30OLDER_CLIENT: Final = ( 

31 "this copytrading CLI is older than the app; use the one inside CopyTrading.app" 

32) 

33 

34 

35class ProtocolMismatch(Exception): 

36 """The app answered with something outside the contract.""" 

37 

38 

39class NoAnswer(AppUnavailable): 

40 """The request was sent, but no answer came in time; what it did is not known.""" 

41 

42 

43class RequestTooLarge(Exception): 

44 """The request line is over the contract's limit, so it is never sent.""" 

45 

46 

47def app_state_root() -> Path: 

48 """Where the Mac app keeps its state.""" 

49 return Path.home() / "Library" / "Application Support" / "CopyTrading" 

50 

51 

52def server_state_root( 

53 environ: Mapping[str, str] = os.environ, platform: str = sys.platform 

54) -> Path: 

55 """Where the headless server keeps its state by default; never the app's folder.""" 

56 if platform == "darwin": 56 ↛ 58line 56 didn't jump to line 58 because the condition on line 56 was always true

57 return Path.home() / "Library" / "Application Support" / "CopyTrading Server" 

58 base = environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state") 

59 return Path(base) / "copytrading-server" 

60 

61 

62def state_root(environ: Mapping[str, str] = os.environ, platform: str = sys.platform) -> Path: 

63 """An explicit state root; else the app's when its socket exists; else the server's.""" 

64 value = environ.get("COPYTRADING_STATE_ROOT") 

65 if value: 65 ↛ 66line 65 didn't jump to line 66 because the condition on line 65 was never true

66 return Path(value) 

67 candidates = [server_state_root(environ, platform)] 

68 if platform == "darwin": 68 ↛ 70line 68 didn't jump to line 70 because the condition on line 68 was always true

69 candidates.insert(0, app_state_root()) 

70 for root in candidates: 70 ↛ 73line 70 didn't jump to line 73 because the loop on line 70 didn't complete

71 if os.path.lexists(root / "control" / "cli.sock"): 

72 return root 

73 return candidates[0] 

74 

75 

76def is_server_socket(environ: Mapping[str, str] = os.environ, platform: str = sys.platform) -> bool: 

77 """The socket found is a headless server's, not the Mac app's. An explicit state root is the 

78 owner's choice; setup then relies on the app being the one that answers `get_setup`.""" 

79 if environ.get("COPYTRADING_STATE_ROOT"): 

80 return False 

81 return state_root(environ, platform) == server_state_root(environ, platform) 

82 

83 

84def socket_path(environ: Mapping[str, str] = os.environ) -> Path: 

85 return state_root(environ) / "control" / "cli.sock" 

86 

87 

88def check_socket(path: Path) -> None: 

89 """Accept only an owner socket inside an owner-only directory, never through a symlink.""" 

90 try: 

91 directory = os.lstat(path.parent) 

92 entry = os.lstat(path) 

93 except FileNotFoundError: 

94 raise AppUnavailable from None 

95 uid = os.getuid() 

96 if ( 

97 not stat.S_ISDIR(directory.st_mode) 

98 or directory.st_uid != uid 

99 or directory.st_mode & 0o077 

100 or not stat.S_ISSOCK(entry.st_mode) 

101 or entry.st_uid != uid 

102 ): 

103 raise UnsafeSocket(str(path)) 

104 

105 

106def new_request_id() -> str: 

107 return uuid4().hex 

108 

109 

110class ControlClient: 

111 def __init__(self, path: Path, *, timeout: float = DEFAULT_TIMEOUT) -> None: 

112 self._path = path 

113 self._timeout = timeout 

114 

115 async def send(self, request: wire.Request) -> wire.Response: 

116 """Send one request on a fresh connection and return its single response.""" 

117 line = wire.REQUEST.dump_json(request) + b"\n" 

118 if len(line) > wire.MAX_LINE_BYTES: 

119 raise RequestTooLarge(len(line)) 

120 check_socket(self._path) 

121 try: 

122 reader, writer = await asyncio.wait_for( 

123 asyncio.open_unix_connection(self._path, limit=MAX_RESPONSE_BYTES), 

124 self._timeout, 

125 ) 

126 except (ConnectionRefusedError, FileNotFoundError, TimeoutError) as exc: 

127 raise AppUnavailable from exc 

128 try: 

129 writer.write(line) 

130 await writer.drain() 

131 except (ConnectionError, TimeoutError) as exc: 

132 raise AppUnavailable from exc 

133 try: 

134 line = await asyncio.wait_for(reader.readline(), self._timeout) 

135 except TimeoutError as exc: 

136 raise NoAnswer(self._timeout) from exc 

137 except (ConnectionError, asyncio.LimitOverrunError) as exc: 

138 raise AppUnavailable from exc 

139 finally: 

140 writer.close() 

141 with contextlib.suppress(ConnectionError): 

142 await writer.wait_closed() 

143 if not line: 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true

144 raise AppUnavailable 

145 try: 

146 response = wire.Response.model_validate_json(line) 

147 except ValidationError as exc: 

148 raise ProtocolMismatch(_mismatch(line)) from exc 

149 if response.request_id not in ("", request.request_id): 149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true

150 raise ProtocolMismatch("response answers a different request") 

151 return response 

152 

153 

154def _mismatch(line: bytes) -> str: 

155 """Why a response could not be read. The CLI and the app ship together, so a well-formed 

156 answer this client cannot read comes from a newer app (see the compatibility rule).""" 

157 try: 

158 payload = json.loads(line) 

159 except ValueError, RecursionError: 

160 return "response is outside the control contract" 

161 if isinstance(payload, dict) and isinstance(payload.get("schema_version"), int): 161 ↛ 164line 161 didn't jump to line 164 because the condition on line 161 was always true

162 if payload.get("ok") is not None or payload.get("error") is not None: 162 ↛ 164line 162 didn't jump to line 164 because the condition on line 162 was always true

163 return OLDER_CLIENT 

164 return "response is outside the control contract"