Coverage for src/copytrading_engine/host/pipe/handlers/restore.py: 82%
76 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"""Backup and restore: create, preview, stage, check, and activate a candidate."""
3import asyncio
4import time
5from dataclasses import dataclass
6from pathlib import Path
7from uuid import uuid4
9from copytrading_engine.backup.manifest import backup_manifest_payload, restore_preview_payload
10from copytrading_engine.backup.service import BackupRestoreService
11from copytrading_engine.execution.application.restore_preflight import (
12 RestoreBrokerCredential,
13 RestoreCandidatePreflight,
14)
15from copytrading_engine.host.pipe.requests import (
16 AbortRestoreCandidateRequest,
17 CompleteRestoreCandidateRequest,
18 CreateBackupRequest,
19 PipeRequest,
20 PrepareRestoreCandidateRequest,
21 PreviewRestoreRequest,
22 RequestHandler,
23 RestoreCandidateStatusRequest,
24 RestorePreflightRequest,
25)
26from copytrading_engine.host.pipe.responses import reply
27from copytrading_engine.host.pipe.services import TradingServices
28from copytrading_engine.host.pipe.session import PipeSession
31@dataclass(frozen=True)
32class _RestorePreflightGrant:
33 candidate_id: str
34 token: str
35 expires_at: float
38class BackupRestoreHandlers:
39 """Back up, then stage, check, and activate a restore candidate; activation ends the session."""
41 def __init__(
42 self,
43 *,
44 backup_restore: BackupRestoreService | None,
45 restore_preflight: RestoreCandidatePreflight | None,
46 trading: TradingServices | None,
47 restore_gated: bool,
48 session: PipeSession,
49 ) -> None:
50 self._backup_restore = backup_restore
51 self._restore_preflight = restore_preflight
52 self._trading = trading
53 self._restore_gated = restore_gated
54 self._session = session
55 self._restore_preflight_grant: _RestorePreflightGrant | None = None
57 def handlers(self) -> dict[type[PipeRequest], RequestHandler]:
58 return {
59 CreateBackupRequest: self._on_create_backup,
60 PreviewRestoreRequest: self._on_preview_restore,
61 PrepareRestoreCandidateRequest: self._on_prepare_restore_candidate,
62 RestoreCandidateStatusRequest: self._on_restore_candidate_status,
63 AbortRestoreCandidateRequest: self._on_abort_restore_candidate,
64 RestorePreflightRequest: self._on_restore_preflight,
65 CompleteRestoreCandidateRequest: self._on_complete_restore_candidate,
66 }
68 async def _on_create_backup(self, request: CreateBackupRequest) -> bytes:
69 if self._backup_restore is None: 69 ↛ 70line 69 didn't jump to line 70 because the condition on line 69 was never true
70 return reply(request.version, request.request_id, error="unavailable")
71 destination = Path(request.destination)
72 if not destination.is_absolute():
73 return reply(request.version, request.request_id, error="invalid_request")
74 manifest = await self._backup_restore.create_backup(destination)
75 return reply(
76 request.version,
77 request.request_id,
78 ok={"type": "backup", "manifest": backup_manifest_payload(manifest)},
79 )
81 async def _on_preview_restore(self, request: PreviewRestoreRequest) -> bytes:
82 if self._backup_restore is None: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true
83 return reply(request.version, request.request_id, error="unavailable")
84 archive_path = Path(request.archive_path)
85 if not archive_path.is_absolute(): 85 ↛ 86line 85 didn't jump to line 86 because the condition on line 85 was never true
86 return reply(request.version, request.request_id, error="invalid_request")
87 staged, preview = await asyncio.to_thread(
88 self._backup_restore.stage_restore,
89 archive_path,
90 self._backup_restore.staging_root,
91 )
92 return reply(
93 request.version,
94 request.request_id,
95 ok={
96 "type": "restore_preview",
97 "preview": restore_preview_payload(preview, staged.name),
98 },
99 )
101 async def _on_prepare_restore_candidate(self, request: PrepareRestoreCandidateRequest) -> bytes:
102 if self._backup_restore is None: 102 ↛ 103line 102 didn't jump to line 103 because the condition on line 102 was never true
103 return reply(request.version, request.request_id, error="unavailable")
104 candidate_id = await asyncio.to_thread(
105 self._backup_restore.prepare_restore_candidate,
106 request.staging_id,
107 )
108 return reply(
109 request.version,
110 request.request_id,
111 ok={"type": "restore_candidate", "candidate_id": candidate_id},
112 )
114 async def _on_restore_candidate_status(self, request: RestoreCandidateStatusRequest) -> bytes:
115 if self._backup_restore is None: 115 ↛ 116line 115 didn't jump to line 116 because the condition on line 115 was never true
116 return reply(request.version, request.request_id, error="unavailable")
117 pending = await asyncio.to_thread(self._backup_restore.pending_restore_candidate)
118 candidate = (
119 None
120 if pending is None
121 else {
122 "candidate_id": pending.candidate_id,
123 "previous_generation": pending.previous_generation,
124 "active_generation": pending.active_generation,
125 "installation_id": pending.installation_id,
126 "environment_ids": list(pending.environment_ids),
127 "account_ids": list(pending.account_ids),
128 "credential_references": list(pending.credential_references),
129 "candidate_valid": pending.candidate_valid,
130 }
131 )
132 return reply(
133 request.version,
134 request.request_id,
135 ok={"type": "restore_candidate_status", "candidate": candidate},
136 )
138 async def _on_abort_restore_candidate(self, request: AbortRestoreCandidateRequest) -> bytes:
139 if self._backup_restore is None: 139 ↛ 140line 139 didn't jump to line 140 because the condition on line 139 was never true
140 return reply(request.version, request.request_id, error="unavailable")
141 await asyncio.to_thread(
142 self._backup_restore.abort_restore_candidate,
143 request.candidate_id,
144 )
145 return reply(
146 request.version,
147 request.request_id,
148 ok={"type": "restore_aborted", "candidate_id": request.candidate_id},
149 )
151 async def _on_restore_preflight(self, request: RestorePreflightRequest) -> bytes:
152 self._restore_preflight_grant = None
153 if not self._restore_gated or self._trading is None or self._restore_preflight is None: 153 ↛ 154line 153 didn't jump to line 154 because the condition on line 153 was never true
154 return reply(request.version, request.request_id, error="unavailable")
155 credentials = tuple(
156 RestoreBrokerCredential(
157 account_id=account.account_id,
158 environment=account.environment,
159 key=account.key,
160 secret=account.secret,
161 )
162 for account in request.accounts
163 )
164 self._trading.lifecycle.register_restore_secrets(
165 tuple(
166 value
167 for account in request.accounts
168 for value in (
169 account.key.get_secret_value(),
170 account.secret.get_secret_value(),
171 )
172 )
173 )
174 result = await asyncio.to_thread(
175 self._restore_preflight.preflight_restore_candidate,
176 request.candidate_id,
177 credentials,
178 )
179 completion_token = None
180 if result.eligible: 180 ↛ 187line 180 didn't jump to line 187 because the condition on line 180 was always true
181 completion_token = uuid4().hex
182 self._restore_preflight_grant = _RestorePreflightGrant(
183 candidate_id=result.candidate_id,
184 token=completion_token,
185 expires_at=time.monotonic() + 120,
186 )
187 return reply(
188 request.version,
189 request.request_id,
190 ok={
191 "type": "restore_preflight",
192 "candidate_id": result.candidate_id,
193 "eligible": result.eligible,
194 "checked_account_count": result.checked_account_count,
195 "blockers": [blocker.value for blocker in result.blockers],
196 "completion_token": completion_token,
197 },
198 )
200 async def _on_complete_restore_candidate(
201 self, request: CompleteRestoreCandidateRequest
202 ) -> bytes:
203 grant = self._restore_preflight_grant
204 self._restore_preflight_grant = None
205 if ( 205 ↛ 213line 205 didn't jump to line 213 because the condition on line 205 was never true
206 not self._restore_gated
207 or self._backup_restore is None
208 or grant is None
209 or grant.candidate_id != request.candidate_id
210 or grant.token != request.completion_token
211 or grant.expires_at < time.monotonic()
212 ):
213 return reply(request.version, request.request_id, error="invalid_request")
214 await asyncio.to_thread(
215 self._backup_restore.complete_restore_candidate,
216 request.candidate_id,
217 )
218 self._session.stop()
219 return reply(
220 request.version,
221 request.request_id,
222 ok={"type": "restore_activated", "candidate_id": request.candidate_id},
223 )