Coverage for src/copytrading_engine/headless/server.py: 75%
132 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"""Compose the engine in this process, start copying, and serve until asked to stop."""
3import asyncio
4import contextlib
5import signal
6import tempfile
7import uuid
8from collections.abc import Callable
9from dataclasses import dataclass
10from pathlib import Path
12from copytrading_engine.bootstrap import compose_engine, persist_installation_id
13from copytrading_engine.control.wire import MAX_LINE_BYTES
14from copytrading_engine.headless.config import ServerSetup
15from copytrading_engine.headless.engine import HeadlessEngine, SetupReport
16from copytrading_engine.headless.owner import (
17 Approve,
18 AskStatus,
19 ListProposals,
20 OwnerAnswer,
21 OwnerRequest,
22 Pause,
23 ProposalChanged,
24 Proposals,
25 Reject,
26 Resume,
27 SetEntries,
28)
29from copytrading_engine.headless.sockets import (
30 MAX_OWNER_LINE_BYTES,
31 OwnerHandler,
32 agent_handler,
33 open_socket,
34 owner_handler,
35 prepare_private_directory,
36)
37from copytrading_engine.trading.domain.config import TradingSecrets
39type Say = Callable[[str], None]
41STATUS_INTERVAL_SECONDS = 30.0
44@dataclass(frozen=True)
45class ServerPaths:
46 """Everything the server keeps, under one owner-only root."""
48 root: Path
50 @property
51 def data(self) -> Path:
52 return self.root / "data"
54 @property
55 def support(self) -> Path:
56 return self.root / "support"
58 @property
59 def logs(self) -> Path:
60 return self.root / "logs"
62 @property
63 def control(self) -> Path:
64 return self.root / "control"
66 @property
67 def agent_socket(self) -> Path:
68 return self.control / "cli.sock"
70 @property
71 def owner_socket(self) -> Path:
72 return self.control / "owner.sock"
74 def prepare(self) -> None:
75 """Create every folder owner-only, refusing any that someone else could reach."""
76 for directory in (self.root, self.data, self.support, self.logs, self.control):
77 prepare_private_directory(directory)
79 def installation_id(self) -> str:
80 """This server's lasting identity, created on first use; the engine checks it."""
81 identity = self.support / "installation-id"
82 instance_id = (
83 identity.read_text(encoding="ascii").strip() if identity.exists() else str(uuid.uuid4())
84 )
85 persist_installation_id(self.support, instance_id)
86 return instance_id
89class _Discard:
90 """The engine's reply stream has no reader here: requests arrive from the sockets."""
92 def write(self, data: bytes) -> None:
93 return None
95 async def drain(self) -> None:
96 return None
99async def check_setup(setup: ServerSetup, secrets: TradingSecrets) -> SetupReport:
100 """Run the app's setup check in a throwaway state folder; nothing is saved or traded."""
101 with tempfile.TemporaryDirectory(prefix="copytrading-check-") as scratch:
102 paths = ServerPaths(Path(scratch).resolve())
103 paths.prepare()
104 async with compose_engine(
105 paths.data,
106 paths.installation_id(),
107 diagnostics_directory=paths.logs,
108 owner_support_directory=paths.support,
109 ) as server:
110 return await HeadlessEngine(server, setup, secrets).validate()
113async def run_server(
114 setup: ServerSetup,
115 secrets: TradingSecrets,
116 paths: ServerPaths,
117 *,
118 say: Say,
119 stop: asyncio.Event | None = None,
120 install_signal_handlers: bool = True,
121) -> None:
122 """Start copying, serve the sockets, and wind down like the app does on quit."""
123 paths.prepare()
124 stop = stop or asyncio.Event()
125 async with compose_engine(
126 paths.data,
127 paths.installation_id(),
128 diagnostics_directory=paths.logs,
129 owner_support_directory=paths.support,
130 ) as server:
131 engine = HeadlessEngine(server, setup, secrets)
132 say("Checking the setup and starting to copy…")
133 await engine.start()
134 reader = asyncio.StreamReader()
135 serving = asyncio.create_task(server.serve(reader, _Discard()))
136 sockets: list[asyncio.Server] = []
137 watcher: asyncio.Task[None] | None = None
138 try:
139 sockets.append(
140 await open_socket(
141 paths.owner_socket,
142 owner_handler(_owner_requests(engine, say)),
143 limit=MAX_OWNER_LINE_BYTES,
144 )
145 )
146 if engine.agent_access != "off": 146 ↛ 152line 146 didn't jump to line 152 because the condition on line 146 was always true
147 sockets.append(
148 await open_socket(
149 paths.agent_socket, agent_handler(engine), limit=MAX_LINE_BYTES
150 )
151 )
152 if install_signal_handlers: 152 ↛ 153line 152 didn't jump to line 153 because the condition on line 152 was never true
153 loop = asyncio.get_running_loop()
154 for signum in (signal.SIGINT, signal.SIGTERM):
155 loop.add_signal_handler(signum, stop.set)
156 configuration = setup.configuration
157 say(
158 f"Copying {len(configuration.profiles)} guru(s) into "
159 f"{len(configuration.accounts)} account(s). Agents: {engine.agent_access}. "
160 f"State: {paths.root}"
161 )
162 say("New accounts start with entries off: `copytrading-server entries enable ID`.")
163 watcher = asyncio.create_task(_report_changes(engine, say))
164 await stop.wait()
165 say("Stopping: pausing copying and finishing in-flight work…")
166 finally:
167 if watcher is not None: 167 ↛ 171line 167 didn't jump to line 171 because the condition on line 167 was always true
168 watcher.cancel()
169 with contextlib.suppress(asyncio.CancelledError):
170 await watcher
171 for listener in sockets:
172 listener.close()
173 await listener.wait_closed()
174 for path in (paths.agent_socket, paths.owner_socket):
175 path.unlink(missing_ok=True)
176 # End of input is how the app says goodbye: the engine pauses and drains.
177 reader.feed_eof()
178 await serving
179 say("Stopped.")
182def _owner_requests(engine: HeadlessEngine, say: Say) -> OwnerHandler:
183 async def handle(request: OwnerRequest) -> OwnerAnswer:
184 match request:
185 case AskStatus():
186 return await engine.status()
187 case SetEntries(account=account, enabled=enabled): 187 ↛ 188line 187 didn't jump to line 188 because the pattern on line 187 never matched
188 changed = await engine.set_entries(account, enabled=enabled)
189 say(f"Entries {'enabled' if enabled else 'disabled'} for {account}.")
190 return changed
191 case ListProposals():
192 return Proposals(items=await engine.proposals())
193 case Approve(proposal_id=proposal_id, digest=digest): 193 ↛ 194line 193 didn't jump to line 194 because the pattern on line 193 never matched
194 proposal = await engine.approve(proposal_id, digest)
195 say(f"Approved {proposal_id}: {proposal.state}.")
196 return ProposalChanged(proposal=proposal)
197 case Reject(proposal_id=proposal_id):
198 proposal = await engine.reject(proposal_id)
199 say(f"Rejected {proposal_id}.")
200 return ProposalChanged(proposal=proposal)
201 case Pause(): 201 ↛ 205line 201 didn't jump to line 205 because the pattern on line 201 always matched
202 status = await engine.pause()
203 say("Copying paused.")
204 return status
205 case Resume():
206 await engine.start()
207 say("Copying resumed.")
208 return await engine.status()
210 return handle
213async def _report_changes(engine: HeadlessEngine, say: Say) -> None:
214 """Print a line whenever copying's state, an account, or the work done changes."""
215 last: str | None = None
216 while True:
217 await asyncio.sleep(STATUS_INTERVAL_SECONDS)
218 try:
219 line = (await engine.status()).summary()
220 except Exception: # noqa: BLE001 - a status line is best effort; the engine logs the cause
221 continue
222 if line != last:
223 say(line)
224 last = line