Coverage for src/copytrading_engine/trading/adapters/operator_queries.py: 83%

232 statements  

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

1"""Project committed source, parser and account evidence for the private UI.""" 

2 

3import datetime as dt 

4import functools 

5import json 

6import sqlite3 

7from contextlib import closing 

8from pathlib import Path 

9from typing import Literal 

10 

11from copytrading_engine.execution.adapters.sqlite_ledger import ( 

12 EXECUTION_SCHEMA, 

13 decode_ledger_snapshot, 

14 feed_events, 

15 message_events, 

16) 

17from copytrading_engine.execution.domain.events import JournalEvent 

18from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot 

19from copytrading_engine.execution.domain.manual_commands import ( 

20 ManualRefusal, 

21 ManualSourceEvidence, 

22) 

23from copytrading_engine.execution.presentation.account_feed import AccountFeedPage, account_feed 

24from copytrading_engine.execution.presentation.guru_performance import REPLAY_KINDS 

25from copytrading_engine.execution.presentation.operator_views import ( 

26 AccountEventPage, 

27 AccountOverview, 

28 DestinationView, 

29 account_overview, 

30 event_page, 

31) 

32from copytrading_engine.parsing.sqlite import record_owner_correction 

33from copytrading_engine.shared.raw_message import RawMessage 

34from copytrading_engine.shared.signals import Instruction, StockSignal 

35from copytrading_engine.trading.adapters.account_records import delete_record 

36from copytrading_engine.trading.presentation.operator_models import ( 

37 GuruPost, 

38 RejectedSourceActivity, 

39 SourceActivity, 

40 SourceActivityPage, 

41 SourceAttachmentEvidence, 

42 SourceEmbedEvidence, 

43 SourceEmbedField, 

44 SourceEventEvidence, 

45) 

46 

47 

48def _has_table(db: sqlite3.Connection, name: str) -> bool: 

49 row = db.execute( 

50 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,) 

51 ).fetchone() 

52 return row is not None 

53 

54 

55def _moment(value: object) -> dt.datetime | None: 

56 """A stored time as an aware moment: ISO text, or epoch seconds from older rows.""" 

57 if value is None: 

58 return None 

59 if isinstance(value, int | float): 59 ↛ 60line 59 didn't jump to line 60 because the condition on line 59 was never true

60 return dt.datetime.fromtimestamp(value, dt.UTC) 

61 moment = dt.datetime.fromisoformat(str(value)) 

62 return moment if moment.tzinfo else moment.replace(tzinfo=dt.UTC) 

63 

64 

65def source_page( 

66 database: Path, 

67 *, 

68 before_seq: int | None, 

69 limit: int, 

70 destinations: dict[str, tuple[DestinationView, ...]], 

71 source_ids: tuple[str, ...] | None = None, 

72 channel: tuple[str, str] | None = None, 

73 channels: tuple[tuple[str, str], ...] | None = None, 

74) -> SourceActivityPage: 

75 """A page of posts, newest first; given `channel` (source, channel ID), only the posts read 

76 for that channel's guru, with no rejected posts; given `channels`, only the posts of those 

77 channels; or, given `source_ids`, exactly those posts however old, with no page and no 

78 rejected posts.""" 

79 if source_ids is None: 

80 if not 1 <= limit <= 100 or (before_seq is not None and before_seq < 1): 80 ↛ 81line 80 didn't jump to line 81 because the condition on line 80 was never true

81 raise ValueError("Invalid source activity page") 

82 where, bound = "(? IS NULL OR capture.seq < ?)", (before_seq, before_seq) 

83 if channel is not None: 

84 # A post is its channel's guru's once it was read for a guru (StockSignal.guru). 

85 where += ( 

86 " AND substr(capture.id,1,?)=?" 

87 " AND json_extract(parser.result,'$.guru_id') IS NOT NULL" 

88 ) 

89 prefix = f"{channel[0]}:{channel[1]}:" 

90 bound = (*bound, len(prefix), prefix) 

91 if channels is not None: 

92 # Only the channels the setup follows: a page of other channels' posts is read for 

93 # nothing and makes a month of Activity many pages long. 

94 prefixes = tuple(f"{source}:{channel_id}:" for source, channel_id in channels) 

95 where += ( 

96 " AND (" + (" OR ".join("substr(capture.id,1,?)=?" for _ in prefixes) or "0") + ")" 

97 ) 

98 bound = (*bound, *(value for prefix in prefixes for value in (len(prefix), prefix))) 

99 else: 

100 limit = max(1, len(source_ids)) 

101 where = f"capture.id IN ({','.join('?' for _ in source_ids)})" 

102 bound = source_ids 

103 if not database.exists(): 103 ↛ 104line 103 didn't jump to line 104 because the condition on line 103 was never true

104 return SourceActivityPage(items=(), rejected_items=()) 

105 with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db: 

106 # The self-test store creates the database before processing first opens the source store. 

107 if not _has_table(db, "source_captures"): 

108 return SourceActivityPage(items=(), rejected_items=()) 

109 rows = db.execute( 

110 "SELECT capture.seq,capture.id,capture.payload,capture.source_at," 

111 "capture.captured_at,capture.mode,capture.confirmed,parser.result," 

112 "delivery.delivered_at,event.event_payload,event.capture_status,event.payload_bytes," 

113 "parser.enqueued_at,parser.completed_at " 

114 "FROM source_captures capture LEFT JOIN parser_inbox parser ON parser.id=capture.id " 

115 "LEFT JOIN parser_signal_deliveries delivery ON delivery.message_id=capture.id " 

116 "LEFT JOIN source_event_evidence event ON event.source_id=capture.id " 

117 f"WHERE {where} ORDER BY capture.seq DESC LIMIT ?", 

118 (*bound, limit), 

119 ).fetchall() 

120 rejected_rows = ( 

121 [] 

122 if source_ids is not None or channel is not None 

123 else db.execute( 

124 "SELECT rejected.id,rejected.payload,rejected.reason,rejected.rejected_at," 

125 "event.event_payload,event.capture_status,event.payload_bytes " 

126 "FROM source_rejected rejected LEFT JOIN source_event_evidence event " 

127 "ON event.source_id=rejected.id ORDER BY rejected.rejected_at DESC," 

128 "rejected.id DESC LIMIT ?", 

129 (limit,), 

130 ).fetchall() 

131 ) 

132 found_ids = tuple(row[1] for row in rows) 

133 attachment_rows = () 

134 if found_ids: 

135 placeholders = ",".join("?" for _ in found_ids) 

136 attachment_rows = db.execute( 

137 "SELECT source_id,evidence_id,attachment_id,filename,content_type,declared_size," 

138 "capture_status,byte_size,sha256,omitted_count " 

139 f"FROM source_attachment_evidence WHERE source_id IN ({placeholders}) " 

140 "ORDER BY source_id,attachment_id", 

141 found_ids, 

142 ).fetchall() 

143 rejected_ids = tuple(row[0] for row in rejected_rows) 

144 rejected_attachment_rows = () 

145 if rejected_ids: 

146 placeholders = ",".join("?" for _ in rejected_ids) 

147 rejected_attachment_rows = db.execute( 

148 "SELECT source_id,evidence_id,attachment_id,filename,content_type,declared_size," 

149 "capture_status,byte_size,sha256,omitted_count " 

150 f"FROM source_rejected_attachment_evidence WHERE source_id IN ({placeholders}) " 

151 "ORDER BY source_id,attachment_id", 

152 rejected_ids, 

153 ).fetchall() 

154 attachments_by_source: dict[str, list[SourceAttachmentEvidence]] = { 

155 source_id: [] for source_id in found_ids 

156 } 

157 for row in attachment_rows: 

158 attachments_by_source[row[0]].append( 

159 SourceAttachmentEvidence( 

160 evidence_id=row[1], 

161 attachment_id=row[2], 

162 filename=row[3], 

163 content_type=row[4], 

164 declared_size=int(row[5]), 

165 status=row[6], 

166 byte_size=int(row[7]) if row[7] is not None else None, 

167 sha256=row[8], 

168 omitted_count=int(row[9]), 

169 ) 

170 ) 

171 rejected_attachments_by_source: dict[str, list[SourceAttachmentEvidence]] = { 

172 source_id: [] for source_id in rejected_ids 

173 } 

174 for row in rejected_attachment_rows: 

175 rejected_attachments_by_source[row[0]].append( 

176 SourceAttachmentEvidence( 

177 evidence_id=row[1], 

178 attachment_id=row[2], 

179 filename=row[3], 

180 content_type=row[4], 

181 declared_size=int(row[5]), 

182 status=row[6], 

183 byte_size=int(row[7]) if row[7] is not None else None, 

184 sha256=row[8], 

185 omitted_count=int(row[9]), 

186 ) 

187 ) 

188 items = [] 

189 for ( 

190 seq, 

191 source_id, 

192 raw, 

193 source_at, 

194 captured_at, 

195 mode, 

196 confirmed, 

197 parsed, 

198 delivered_at, 

199 event_payload, 

200 event_status, 

201 event_bytes, 

202 read_started_at, 

203 read_at, 

204 ) in rows: 

205 source = RawMessage.model_validate_json(raw) 

206 decision = StockSignal.model_validate_json(parsed) if parsed else None 

207 source_event = _source_event_view( 

208 event_payload, 

209 _source_event_status(event_status or "missing"), 

210 int(event_bytes or 0), 

211 source.text, 

212 tuple(attachments_by_source[source_id]), 

213 ) 

214 items.append( 

215 SourceActivity( 

216 sequence=seq, 

217 source_id=source_id, 

218 author_id=source.author_id, 

219 # The capture's sequence: the revision a manual correction is checked against. 

220 source_revision=seq, 

221 source_at=dt.datetime.fromisoformat(source_at), 

222 captured_at=dt.datetime.fromisoformat(captured_at), 

223 text=source.text, 

224 capture_status="historical" 

225 if mode == "historical" 

226 else "delivered" 

227 if confirmed 

228 else "pending", 

229 parse_status="complete" 

230 if decision 

231 else "pending" 

232 if mode == "live" 

233 else "not_applicable", 

234 delivery_status="delivered" 

235 if delivered_at 

236 else "pending" 

237 if parsed 

238 else "not_ready", 

239 decision=decision.decision if decision else None, 

240 parser_reason=decision.reason if decision else None, 

241 parser_profile=decision.parser_profile if decision else None, 

242 interpreted_by=decision.model if decision else None, 

243 instructions=decision.instructions if decision else (), 

244 stops=decision.stops if decision else (), 

245 suggested=decision.suggested if decision else (), 

246 reading=decision.reading if decision else None, 

247 guru_id=decision.guru if decision else None, 

248 profile_revision=decision.profile_revision if decision else None, 

249 source_event=source_event, 

250 destinations=destinations.get(source_id, ()), 

251 read_started_at=_moment(read_started_at), 

252 read_at=_moment(read_at), 

253 delivered_at=_moment(delivered_at), 

254 ) 

255 ) 

256 return SourceActivityPage( 

257 items=tuple(items), 

258 rejected_items=tuple( 

259 RejectedSourceActivity( 

260 source_id=row[0], 

261 rejected_at=dt.datetime.fromisoformat(row[3]), 

262 reason=row[2], 

263 source_event=_source_event_view( 

264 row[4], 

265 _source_event_status(row[5] or "missing"), 

266 int(row[6] or 0), 

267 _rejected_fallback_text(row[1]), 

268 tuple(rejected_attachments_by_source[row[0]]), 

269 ), 

270 ) 

271 for row in rejected_rows 

272 ), 

273 next_before_seq=items[-1].sequence if source_ids is None and len(items) == limit else None, 

274 ) 

275 

276 

277# Stored times keep their own offset, which shifts their text by at most this much from UTC. 

278_OFFSET_SLACK = dt.timedelta(hours=14) 

279 

280 

281def guru_posts(database: Path, *, since: dt.datetime) -> tuple[GuruPost, ...]: 

282 """Every read post a guru made from `since` on, oldest first.""" 

283 if not database.exists(): 

284 return () 

285 with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db: 

286 if not _has_table(db, "source_captures") or not _has_table(db, "parser_inbox"): 286 ↛ 287line 286 didn't jump to line 287 because the condition on line 286 was never true

287 return () 

288 # The text comparison only narrows the scan; each time is compared exactly below. 

289 rows = db.execute( 

290 "SELECT capture.id,capture.source_at,parser.result,parser.enqueued_at," 

291 "parser.completed_at FROM source_captures capture " 

292 "JOIN parser_inbox parser ON parser.id=capture.id " 

293 "WHERE parser.result IS NOT NULL AND capture.source_at >= ? ORDER BY capture.seq", 

294 ((since - _OFFSET_SLACK).astimezone(dt.UTC).replace(tzinfo=None).isoformat(),), 

295 ).fetchall() 

296 posts = [] 

297 for source_id, source_at, parsed, read_started_at, read_at in rows: 

298 posted = _moment(source_at) 

299 guru_id = StockSignal.model_validate_json(parsed).guru 

300 if posted is None or posted < since or guru_id is None: 

301 continue 

302 posts.append( 

303 GuruPost( 

304 source_id=source_id, 

305 guru_id=guru_id, 

306 source_at=posted, 

307 read_started_at=_moment(read_started_at), 

308 read_at=_moment(read_at), 

309 ) 

310 ) 

311 return tuple(posts) 

312 

313 

314def _rejected_fallback_text(serialized: str) -> str: 

315 try: 

316 payload = json.loads(serialized) 

317 except json.JSONDecodeError, TypeError: 

318 return "" 

319 if not isinstance(payload, dict): 319 ↛ 320line 319 didn't jump to line 320 because the condition on line 319 was never true

320 return "" 

321 text = payload.get("text") 

322 return text if isinstance(text, str) else "" 

323 

324 

325def _source_event_view( 

326 serialized: str | None, 

327 capture_status: Literal["complete", "oversize", "missing"], 

328 payload_bytes: int, 

329 fallback_text: str, 

330 attachments: tuple[SourceAttachmentEvidence, ...], 

331) -> SourceEventEvidence: 

332 payload: dict[str, object] = {} 

333 if serialized is not None: 333 ↛ 340line 333 didn't jump to line 340 because the condition on line 333 was always true

334 try: 

335 decoded = json.loads(serialized) 

336 if isinstance(decoded, dict): 336 ↛ 340line 336 didn't jump to line 340 because the condition on line 336 was always true

337 payload = decoded 

338 except json.JSONDecodeError, TypeError: 

339 pass 

340 embeds: list[SourceEmbedEvidence] = [] 

341 raw_embeds = payload.get("embeds") 

342 if isinstance(raw_embeds, list): 342 ↛ 367line 342 didn't jump to line 367 because the condition on line 342 was always true

343 for raw_embed in raw_embeds: 

344 if not isinstance(raw_embed, dict): 344 ↛ 345line 344 didn't jump to line 345 because the condition on line 344 was never true

345 continue 

346 fields: list[SourceEmbedField] = [] 

347 raw_fields = raw_embed.get("fields") 

348 if isinstance(raw_fields, list): 348 ↛ 359line 348 didn't jump to line 359 because the condition on line 348 was always true

349 for raw_field in raw_fields: 

350 if not isinstance(raw_field, dict): 350 ↛ 351line 350 didn't jump to line 351 because the condition on line 350 was never true

351 continue 

352 fields.append( 

353 SourceEmbedField( 

354 name=str(raw_field.get("name") or ""), 

355 value=str(raw_field.get("value") or ""), 

356 inline=bool(raw_field.get("inline", False)), 

357 ) 

358 ) 

359 title, description = raw_embed.get("title"), raw_embed.get("description") 

360 embeds.append( 

361 SourceEmbedEvidence( 

362 title=title if isinstance(title, str) else None, 

363 description=description if isinstance(description, str) else None, 

364 fields=tuple(fields), 

365 ) 

366 ) 

367 content = payload.get("content") 

368 raw_omitted = payload.get("attachments_omitted", 0) 

369 omitted = int(raw_omitted) if type(raw_omitted) is int and raw_omitted >= 0 else 0 

370 omitted = max(omitted, *(item.omitted_count for item in attachments), 0) 

371 event_type = payload.get("event_type") 

372 message_id = payload.get("message_id") 

373 channel_id = payload.get("channel_id") 

374 author_id = payload.get("author_id") 

375 timestamp = payload.get("timestamp") 

376 return SourceEventEvidence( 

377 event_type=event_type if isinstance(event_type, str) else "unknown", 

378 message_id=message_id if isinstance(message_id, str) else None, 

379 channel_id=channel_id if isinstance(channel_id, str) else None, 

380 author_id=author_id if isinstance(author_id, str) else None, 

381 timestamp=timestamp if isinstance(timestamp, str) else None, 

382 content=content if isinstance(content, str) else fallback_text, 

383 embeds=tuple(embeds), 

384 attachments=attachments, 

385 attachments_omitted=omitted, 

386 capture_status=capture_status, 

387 payload_bytes=payload_bytes, 

388 ) 

389 

390 

391def _source_event_status(value: str) -> Literal["complete", "oversize", "missing"]: 

392 if value == "complete": 392 ↛ 394line 392 didn't jump to line 394 because the condition on line 392 was always true

393 return "complete" 

394 if value == "oversize": 

395 return "oversize" 

396 if value == "missing": 

397 return "missing" 

398 raise ValueError("Persisted source event has an invalid capture status") 

399 

400 

401def manual_source_evidence(database: Path, source_id: str) -> ManualSourceEvidence: 

402 """Read a complete live source and accepted review parse without mutating it.""" 

403 if not database.exists(): 403 ↛ 404line 403 didn't jump to line 404 because the condition on line 403 was never true

404 raise ManualRefusal("post_unavailable") 

405 with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db: 

406 row = db.execute( 

407 "SELECT capture.seq,capture.payload,capture.source_at,capture.mode," 

408 "capture.confirmed,parser.result " 

409 "FROM source_captures capture LEFT JOIN parser_inbox parser ON parser.id=capture.id " 

410 "WHERE capture.id=?", 

411 (source_id,), 

412 ).fetchone() 

413 if row is None: 413 ↛ 414line 413 didn't jump to line 414 because the condition on line 413 was never true

414 raise ManualRefusal("post_unavailable") 

415 source_revision, raw, source_at, mode, confirmed, parsed = row 

416 if mode != "live" or not confirmed or parsed is None: 

417 raise ManualRefusal("post_unavailable") 

418 source = RawMessage.model_validate_json(raw) 

419 signal = StockSignal.model_validate_json(parsed) 

420 if source.identity != source_id or signal.text != source.text: 420 ↛ 421line 420 didn't jump to line 421 because the condition on line 420 was never true

421 raise ManualRefusal("post_unavailable") 

422 if signal.decision == "ignore": 422 ↛ 423line 422 didn't jump to line 423 because the condition on line 422 was never true

423 raise ManualRefusal("post_ignored") 

424 return ManualSourceEvidence( 

425 source_id=source_id, 

426 source_revision=source_revision, 

427 source_at=dt.datetime.fromisoformat(source_at), 

428 text=source.text, 

429 accepted_interpretation=signal, 

430 ) 

431 

432 

433def historical_source_message(database: Path, source_id: str) -> RawMessage: 

434 """Read the exact captured historical payload without changing its timestamp or mode.""" 

435 if not database.exists() or not 1 <= len(source_id) <= 256: 435 ↛ 436line 435 didn't jump to line 436 because the condition on line 435 was never true

436 raise ValueError("historical_source_unavailable") 

437 with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db: 

438 row = db.execute( 

439 "SELECT payload,mode FROM source_captures WHERE id=?", (source_id,) 

440 ).fetchone() 

441 if row is None or row[1] != "historical": 

442 raise ValueError("historical_source_unavailable") 

443 try: 

444 source = RawMessage.model_validate_json(row[0]) 

445 except ValueError: 

446 raise ValueError("historical_source_unavailable") from None 

447 if source.identity != source_id: 447 ↛ 448line 447 didn't jump to line 448 because the condition on line 447 was never true

448 raise ValueError("historical_source_unavailable") 

449 return source 

450 

451 

452@functools.lru_cache(maxsize=8) 

453def _decoded_snapshot(raw: str) -> LedgerSnapshot: 

454 """A ledger row decoded once per content: every screen reads the same few accounts every few 

455 seconds, and decoding a busy account's row costs far more than reading it (the snapshot is 

456 frozen, so sharing it is safe).""" 

457 return decode_ledger_snapshot(raw) 

458 

459 

460def _retained_snapshot(db: sqlite3.Connection) -> LedgerSnapshot: 

461 revision = db.execute( 

462 "SELECT revision FROM copytrading_engine_schema_revisions WHERE component='execution'" 

463 ).fetchone() 

464 if revision != (EXECUTION_SCHEMA.revision,): 464 ↛ 465line 464 didn't jump to line 465 because the condition on line 464 was never true

465 raise RuntimeError("Unsupported retained execution schema revision") 

466 identity = db.execute( 

467 "SELECT environment,account_id FROM identity WHERE singleton=1" 

468 ).fetchone() 

469 row = db.execute("SELECT data FROM snapshot WHERE singleton=1").fetchone() 

470 if identity is None or row is None: 

471 raise RuntimeError("Retained account evidence is incomplete") 

472 snapshot = _decoded_snapshot(row[0]) 

473 if (snapshot.environment, snapshot.account_id) != identity: 473 ↛ 474line 473 didn't jump to line 474 because the condition on line 473 was never true

474 raise RuntimeError("Retained account identity mismatch") 

475 return snapshot 

476 

477 

478def retained_feed(path: Path, *, before_seq: int | None, limit: int) -> AccountFeedPage: 

479 """A retained account's feed, read without binding a broker or a writer.""" 

480 with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db: 

481 snapshot = _retained_snapshot(db) 

482 rows = feed_events(db, before_seq, limit) 

483 return account_feed(path.parent.name, snapshot, rows, limit) 

484 

485 

486def retained_fills(path: Path) -> tuple[LedgerSnapshot, tuple[JournalEvent, ...]]: 

487 """A retained account's ledger and, from the same read transaction, every journal event that 

488 changes what a lot holds by a sale or a fill, oldest first.""" 

489 kinds = ",".join("?" * len(REPLAY_KINDS)) 

490 with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db: 

491 db.execute("BEGIN") 

492 snapshot = _retained_snapshot(db) 

493 rows = db.execute( 

494 f"SELECT event FROM journal WHERE json_extract(event, '$.payload.kind') IN ({kinds}) " 

495 "ORDER BY id", 

496 REPLAY_KINDS, 

497 ).fetchall() 

498 return snapshot, tuple(JournalEvent.model_validate_json(raw) for (raw,) in rows) 

499 

500 

501def retained_account( 

502 path: Path, *, before_seq: int | None = None, limit: int = 50 

503) -> tuple[AccountOverview, LedgerSnapshot, AccountEventPage]: 

504 """Read retained evidence without binding another broker or account writer.""" 

505 if not 1 <= limit <= 100 or (before_seq is not None and before_seq < 1): 505 ↛ 506line 505 didn't jump to line 506 because the condition on line 505 was never true

506 raise ValueError("Invalid account event page") 

507 with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db: 

508 snapshot = _retained_snapshot(db) 

509 rows = db.execute( 

510 "SELECT id,event FROM journal WHERE (? IS NULL OR id < ?) ORDER BY id DESC LIMIT ?", 

511 (before_seq, before_seq, limit), 

512 ).fetchall() 

513 newest = db.execute("SELECT event FROM journal ORDER BY id DESC LIMIT 1").fetchone() 

514 overview = account_overview( 

515 snapshot, 

516 None, 

517 local_account_id=path.parent.name, 

518 active_configuration=False, 

519 readiness="inactive_evidence", 

520 balance=None, 

521 last_activity_at=JournalEvent.model_validate_json(newest[0]).at if newest else None, 

522 ) 

523 events = event_page( 

524 path.parent.name, 

525 tuple((seq, JournalEvent.model_validate_json(raw)) for seq, raw in rows), 

526 limit, 

527 ) 

528 return overview, snapshot, events 

529 

530 

531class SQLiteOperatorEvidence: 

532 """The OperatorEvidence port over read-only SQLite connections.""" 

533 

534 def source_page( 

535 self, 

536 database: Path, 

537 *, 

538 before_seq: int | None, 

539 limit: int, 

540 destinations: dict[str, tuple[DestinationView, ...]], 

541 source_ids: tuple[str, ...] | None = None, 

542 channel: tuple[str, str] | None = None, 

543 channels: tuple[tuple[str, str], ...] | None = None, 

544 ) -> SourceActivityPage: 

545 return source_page( 

546 database, 

547 before_seq=before_seq, 

548 limit=limit, 

549 destinations=destinations, 

550 source_ids=source_ids, 

551 channel=channel, 

552 channels=channels, 

553 ) 

554 

555 def guru_posts(self, database: Path, *, since: dt.datetime) -> tuple[GuruPost, ...]: 

556 return guru_posts(database, since=since) 

557 

558 def retained_account( 

559 self, path: Path, *, before_seq: int | None = None, limit: int = 50 

560 ) -> tuple[AccountOverview, LedgerSnapshot, AccountEventPage]: 

561 return retained_account(path, before_seq=before_seq, limit=limit) 

562 

563 def retained_feed(self, path: Path, *, before_seq: int | None, limit: int) -> AccountFeedPage: 

564 return retained_feed(path, before_seq=before_seq, limit=limit) 

565 

566 def retained_fills(self, path: Path) -> tuple[LedgerSnapshot, tuple[JournalEvent, ...]]: 

567 return retained_fills(path) 

568 

569 def retained_message_events( 

570 self, path: Path, message_ids: set[str] 

571 ) -> tuple[JournalEvent, ...]: 

572 with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db: 

573 return message_events(db, message_ids) 

574 

575 def manual_source_evidence(self, database: Path, source_id: str) -> ManualSourceEvidence: 

576 return manual_source_evidence(database, source_id) 

577 

578 def record_owner_correction( 

579 self, 

580 database: Path, 

581 source_id: str, 

582 instructions: tuple[Instruction, ...], 

583 at: dt.datetime, 

584 ) -> None: 

585 record_owner_correction(database, source_id, instructions, at) 

586 

587 def historical_source_message(self, database: Path, source_id: str) -> RawMessage: 

588 return historical_source_message(database, source_id) 

589 

590 def delete_record(self, root: Path, account_id: str) -> str | None: 

591 return delete_record(root, account_id)