Coverage for src/copytrading_engine/headless/engine.py: 93%
120 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""Drive the engine's request server the way the app does, from inside the server process."""
3import asyncio
4import json
5import time
6import uuid
7from collections.abc import Awaitable, Callable
8from typing import Any
10from pydantic import BaseModel, ConfigDict
12from copytrading_engine.control.service import SETUP_IN_APP_ONLY
13from copytrading_engine.control.wire import SETUP_OPERATIONS, ErrorBody, ProposalView, Response
14from copytrading_engine.headless.config import AgentAccess, ServerSetup
15from copytrading_engine.headless.owner import CopyingStatus, EntriesChanged, proposal_from_engine
16from copytrading_engine.host.pipe.server import PipeServer
17from copytrading_engine.trading.domain.config import TradingSecrets
19# The ok body of an engine reply. It stays inside this module: callers get typed views.
20type Reply = dict[str, Any]
23class ConnectionCheck(BaseModel):
24 model_config = ConfigDict(frozen=True, extra="ignore")
26 name: str
27 state: str
28 subject: str | None = None
29 environment: str | None = None
30 reason_code: str | None = None
32 @property
33 def passed(self) -> bool:
34 return self.state in {"ready", "not_configured"}
37class SetupReport(BaseModel):
38 """The setup check, as the app's Check Setup shows it."""
40 model_config = ConfigDict(frozen=True, extra="ignore")
42 activatable: bool
43 checks: tuple[ConnectionCheck, ...] = ()
46ACTIVATION_TIMEOUT_SECONDS = 120.0
49class EngineRefused(Exception):
50 """The engine answered a request with an error code; the message says which."""
52 def __init__(self, operation: str, code: str, message: str | None = None) -> None:
53 detail = f"{operation} failed: {code}" + (f" ({message})" if message else "")
54 super().__init__(detail)
55 self.code = code
58class SetupNotReady(Exception):
59 """The setup check found problems, so copying did not start."""
61 def __init__(self, report: SetupReport) -> None:
62 super().__init__("The setup check did not pass.")
63 self.report = report
66class HeadlessEngine:
67 """One request at a time into the engine, exactly as the app's pipe delivered them."""
69 def __init__(
70 self,
71 server: PipeServer,
72 setup: ServerSetup,
73 secrets: TradingSecrets,
74 *,
75 clock: Callable[[], float] = time.monotonic,
76 sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
77 ) -> None:
78 self._server = server
79 self._setup = setup
80 self._secrets = secrets
81 self._lock = asyncio.Lock()
82 self._clock = clock
83 self._sleep = sleep
85 @property
86 def agent_access(self) -> AgentAccess:
87 return self._setup.agent_access
89 async def request(self, operation: str, **fields: object) -> Reply:
90 """Send one request and return its ok body, or raise EngineRefused.
92 The engine's own request validation runs on every call, as it does for the app; the
93 lock keeps the one-request-at-a-time order the app's pipe guaranteed.
94 """
95 envelope = {"version": 1, "request_id": uuid.uuid4().hex, "operation": operation}
96 line = json.dumps(envelope | fields, separators=(",", ":")).encode()
97 async with self._lock:
98 raw = await self._server.handle_line(line)
99 response = json.loads(raw)
100 if "error" in response:
101 error = response["error"]
102 raise EngineRefused(operation, error.get("code", "unknown"), error.get("message"))
103 return response["ok"]
105 async def validate(self) -> SetupReport:
106 """Check every connection and the setup; nothing is saved or traded."""
107 report, _token = await self._validate()
108 return report
110 async def start(self) -> None:
111 """Check the setup, start copying, and wait until the engine reports it running."""
112 report, token = await self._validate()
113 if token is None:
114 raise SetupNotReady(report)
115 activation_id = str(uuid.uuid4())
116 await self.request(
117 "start_trading",
118 configuration=self._configuration(),
119 secrets=self._secret_values(),
120 validation_token=token,
121 activation_id=activation_id,
122 )
123 deadline = self._clock() + ACTIVATION_TIMEOUT_SECONDS
124 while True:
125 reply = await self.request("get_trading_activation", activation_id=activation_id)
126 activation = reply["activation"]
127 if activation["phase"] != "starting":
128 if activation["phase"] != "ready":
129 raise EngineRefused(
130 "start_trading", activation.get("error_code") or activation["phase"]
131 )
132 return
133 if self._clock() > deadline: 133 ↛ 134line 133 didn't jump to line 134 because the condition on line 133 was never true
134 raise EngineRefused("start_trading", "activation_timeout")
135 await self._sleep(0.5)
137 async def status(self) -> CopyingStatus:
138 return CopyingStatus.model_validate((await self.request("get_trading_status"))["trading"])
140 async def pause(self) -> CopyingStatus:
141 return CopyingStatus.model_validate((await self.request("pause_trading"))["trading"])
143 async def set_entries(self, account_id: str, *, enabled: bool) -> EntriesChanged:
144 command = {
145 "command_id": f"server-{uuid.uuid4().hex}",
146 "account_id": account_id,
147 "action": "resume" if enabled else "pause",
148 }
149 control = (await self.request("control_account", command=command))["control"]
150 return EntriesChanged(account_id=account_id, entry_permission=control["entry_permission"])
152 async def proposals(self) -> tuple[ProposalView, ...]:
153 items = (await self.request("list_proposals"))["proposals"]
154 return tuple(proposal_from_engine(item) for item in items)
156 async def approve(self, proposal_id: str, digest: str) -> ProposalView:
157 reply = await self.request("approve_proposal", proposal_id=proposal_id, digest=digest)
158 return proposal_from_engine(reply["proposal"])
160 async def reject(self, proposal_id: str) -> ProposalView:
161 reply = await self.request("reject_proposal", proposal_id=proposal_id)
162 return proposal_from_engine(reply["proposal"])
164 async def relay_agent_line(self, line: str, caller_pid: int | None) -> str:
165 """One agent request, with the owner's chosen access, answered as a contract line."""
166 if self.agent_access == "off":
167 raise EngineRefused("control", "access_off")
168 setup = _setup_request(line)
169 if setup is not None:
170 # A setup request may carry a key; a server is set up in copytrading.toml, so the
171 # line is answered here and never reaches the engine.
172 refusal = ErrorBody(code="unavailable", message=SETUP_IN_APP_ONLY)
173 return Response(request_id=setup, error=refusal).model_dump_json()
174 context = {
175 "access_level": self.agent_access,
176 "unlocked": True,
177 "caller_pid": caller_pid,
178 "caller_path": None,
179 }
180 reply = await self.request("control", line=line, context=context)
181 return reply["line"]
183 async def _validate(self) -> tuple[SetupReport, str | None]:
184 reply = await self.request(
185 "validate_trading",
186 configuration=self._configuration(),
187 secrets=self._secret_values(),
188 )
189 return SetupReport.model_validate(reply["report"]), reply.get("activation_token")
191 def _configuration(self) -> Reply:
192 return self._setup.configuration.model_dump(mode="json")
194 def _secret_values(self) -> Reply:
195 secrets = self._secrets
196 return {
197 "discord_token": secrets.discord_token.get_secret_value(),
198 "provider_api_key": secrets.provider_api_key.get_secret_value(),
199 "brokers": [
200 {
201 "account_id": broker.account_id,
202 "key": broker.key.get_secret_value(),
203 "secret": broker.secret.get_secret_value(),
204 }
205 for broker in secrets.brokers
206 ],
207 "notification_token": (
208 None
209 if secrets.notification_token is None
210 else secrets.notification_token.get_secret_value()
211 ),
212 }
215def _setup_request(line: str) -> str | None:
216 """The request ID of a setup request (possibly empty), or None for any other line."""
217 try:
218 payload = json.loads(line)
219 except ValueError, RecursionError:
220 return None
221 if not isinstance(payload, dict) or payload.get("operation") not in SETUP_OPERATIONS:
222 return None
223 request_id = payload.get("request_id")
224 return request_id if isinstance(request_id, str) and 0 < len(request_id) <= 128 else ""