askrobots / dbbasic-web
Public
A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.
Dan Quellhorst
Replace multipart parser with stdlib-only implementation
eb957a2
9 months, 2 weeks ago
History
bus.py · 1.3 KB · 39 lines
| 1 | """Message bus using dbbasic-pipe (Unix pipes, TSV streams)""" |
| 2 | import json |
| 3 | from typing import AsyncIterator |
| 4 | from dbbasic.pipe import Pipe |
| 5 | from .settings import DATA_DIR |
| 6 | |
| 7 | |
| 8 | class EventBus: |
| 9 | """Event bus using TSV-based streams (no Redis needed)""" |
| 10 | |
| 11 | def __init__(self, stream_dir: str = None): |
| 12 | self.stream_dir = stream_dir or str(DATA_DIR / "streams") |
| 13 | |
| 14 | def _get_pipe(self, stream: str) -> Pipe: |
| 15 | """Get or create a pipe for a stream""" |
| 16 | return Pipe(f"{self.stream_dir}/{stream}.tsv") |
| 17 | |
| 18 | async def publish(self, stream: str, event: dict) -> str: |
| 19 | """Publish an event to a stream""" |
| 20 | pipe = self._get_pipe(stream) |
| 21 | event_json = json.dumps(event) |
| 22 | pipe.write({"data": event_json}) |
| 23 | return event_json |
| 24 | |
| 25 | async def consume(self, stream: str, group: str = "default", consumer: str = "consumer") -> AsyncIterator[dict]: |
| 26 | """Consume events from a stream""" |
| 27 | pipe = self._get_pipe(stream) |
| 28 | |
| 29 | # Read from pipe |
| 30 | for row in pipe.read(): |
| 31 | data = json.loads(row.get("data", "{}")) |
| 32 | yield {"data": data} |
| 33 | |
| 34 | def publish_sync(self, stream: str, event: dict) -> str: |
| 35 | """Synchronous publish (for non-async contexts)""" |
| 36 | pipe = self._get_pipe(stream) |
| 37 | event_json = json.dumps(event) |
| 38 | pipe.write({"data": event_json}) |
| 39 | return event_json |