import json import time from collections.abc import AsyncIterator from pathlib import Path from app.bars.models import Bar class Recorder: def __init__(self, path: str | Path): self.path = Path(path) async def record(self, stream: AsyncIterator[Bar]) -> AsyncIterator[Bar]: self.path.parent.mkdir(parents=True, exist_ok=True) with self.path.open("a", encoding="utf-8") as tape: async for bar in stream: row = {"arrival_t": time.time(), "bar": bar.to_dict()} tape.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n") tape.flush() yield bar