|
| 1 | +""" |
| 2 | +AsyncQueue - In-process event processing with background workers. |
| 3 | +
|
| 4 | +This queue implementation uses asyncio.Queue to decouple API request handling |
| 5 | +from event processing. Events are enqueued quickly, then processed by background |
| 6 | +workers in parallel. |
| 7 | +
|
| 8 | +Use Case: |
| 9 | +- Single-server deployment with concurrent processing |
| 10 | +- Decouple API response time from processing time |
| 11 | +- Parallel processing with configurable workers |
| 12 | +
|
| 13 | +Trade-offs: |
| 14 | +- ✅ Fast API responses (enqueue is O(1)) |
| 15 | +- ✅ Parallel processing (multiple workers) |
| 16 | +- ✅ Simple: No external dependencies |
| 17 | +- ❌ No persistence: Events lost on crash |
| 18 | +- ❌ No horizontal scaling: Single process only |
| 19 | +
|
| 20 | +Evolution Path: |
| 21 | +- DirectQueue: Inline processing (no queue) |
| 22 | +- AsyncQueue: In-process workers (this file) |
| 23 | +- PubSubQueue: Distributed workers (future) |
| 24 | +""" |
| 25 | + |
| 26 | +import asyncio |
| 27 | +import logging |
| 28 | +from typing import TYPE_CHECKING |
| 29 | + |
| 30 | +from eventkit.schema.raw import RawEvent |
| 31 | + |
| 32 | +if TYPE_CHECKING: |
| 33 | + from eventkit.processing.processor import Processor |
| 34 | + |
| 35 | +logger = logging.getLogger(__name__) |
| 36 | + |
| 37 | + |
| 38 | +class AsyncQueue: |
| 39 | + """ |
| 40 | + In-process queue with background workers. |
| 41 | +
|
| 42 | + Events are added to an asyncio.Queue, then processed by N worker tasks |
| 43 | + running in the background. This decouples API request handling from |
| 44 | + event processing. |
| 45 | +
|
| 46 | + Example: |
| 47 | + >>> from eventkit.processing.processor import Processor |
| 48 | + >>> from eventkit.queues.async_queue import AsyncQueue |
| 49 | + >>> |
| 50 | + >>> processor = Processor(adapter, sequencer, buffer, error_store) |
| 51 | + >>> queue = AsyncQueue(processor, num_workers=4) |
| 52 | + >>> |
| 53 | + >>> await queue.start() |
| 54 | + >>> await queue.enqueue(raw_event) # Returns immediately |
| 55 | + >>> # Workers process in background |
| 56 | + >>> await queue.stop() # Drains queue before stopping |
| 57 | + """ |
| 58 | + |
| 59 | + def __init__(self, processor: "Processor", num_workers: int = 4): |
| 60 | + """ |
| 61 | + Initialize AsyncQueue. |
| 62 | +
|
| 63 | + Args: |
| 64 | + processor: The processor that will handle events |
| 65 | + num_workers: Number of background worker tasks (default: 4) |
| 66 | + """ |
| 67 | + self.processor = processor |
| 68 | + self.num_workers = num_workers |
| 69 | + self.queue: asyncio.Queue[RawEvent] = asyncio.Queue() |
| 70 | + self.workers: list[asyncio.Task[None]] = [] |
| 71 | + self._stop_event = asyncio.Event() |
| 72 | + |
| 73 | + async def enqueue(self, event: RawEvent) -> None: |
| 74 | + """ |
| 75 | + Add event to queue (non-blocking). |
| 76 | +
|
| 77 | + Returns immediately after adding to queue. Background workers |
| 78 | + will process the event asynchronously. |
| 79 | +
|
| 80 | + Args: |
| 81 | + event: The raw event to process |
| 82 | + """ |
| 83 | + await self.queue.put(event) |
| 84 | + logger.debug(f"Event enqueued: queue_size={self.queue.qsize()}") |
| 85 | + |
| 86 | + async def start(self) -> None: |
| 87 | + """ |
| 88 | + Start background workers and processor. |
| 89 | +
|
| 90 | + Creates N worker tasks that continuously pull from the queue |
| 91 | + and process events. |
| 92 | + """ |
| 93 | + # Start processor (starts buffer flusher) |
| 94 | + await self.processor.start() |
| 95 | + |
| 96 | + # Start worker tasks |
| 97 | + self._stop_event.clear() |
| 98 | + for i in range(self.num_workers): |
| 99 | + worker = asyncio.create_task(self._worker(worker_id=i)) |
| 100 | + self.workers.append(worker) |
| 101 | + |
| 102 | + logger.info(f"AsyncQueue started with {self.num_workers} workers") |
| 103 | + |
| 104 | + async def stop(self) -> None: |
| 105 | + """ |
| 106 | + Gracefully shutdown: drain queue, stop workers, stop processor. |
| 107 | +
|
| 108 | + 1. Wait for queue to drain (process remaining events) |
| 109 | + 2. Signal workers to stop |
| 110 | + 3. Wait for workers to finish |
| 111 | + 4. Stop processor (flush buffers) |
| 112 | + """ |
| 113 | + logger.info("AsyncQueue stopping - draining queue") |
| 114 | + |
| 115 | + # Wait for queue to drain |
| 116 | + await self.queue.join() |
| 117 | + |
| 118 | + # Signal workers to stop |
| 119 | + self._stop_event.set() |
| 120 | + |
| 121 | + # Wait for all workers to finish |
| 122 | + await asyncio.gather(*self.workers, return_exceptions=True) |
| 123 | + self.workers.clear() |
| 124 | + |
| 125 | + # Stop processor (flush buffers) |
| 126 | + await self.processor.stop() |
| 127 | + |
| 128 | + logger.info("AsyncQueue stopped") |
| 129 | + |
| 130 | + async def _worker(self, worker_id: int) -> None: |
| 131 | + """ |
| 132 | + Background worker that processes events from queue. |
| 133 | +
|
| 134 | + Continuously pulls events from queue and calls processor.process_event() |
| 135 | + until stop signal is received. |
| 136 | +
|
| 137 | + Args: |
| 138 | + worker_id: ID for logging purposes |
| 139 | + """ |
| 140 | + logger.debug(f"Worker {worker_id} started") |
| 141 | + |
| 142 | + while not self._stop_event.is_set(): |
| 143 | + try: |
| 144 | + # Wait for event with timeout (check stop signal periodically) |
| 145 | + event = await asyncio.wait_for(self.queue.get(), timeout=0.1) |
| 146 | + |
| 147 | + # Process event |
| 148 | + try: |
| 149 | + await self.processor.process_event(event) |
| 150 | + except Exception as e: |
| 151 | + logger.error(f"Worker {worker_id} error processing event: {e}") |
| 152 | + finally: |
| 153 | + # Mark task as done (for queue.join()) |
| 154 | + self.queue.task_done() |
| 155 | + |
| 156 | + except TimeoutError: |
| 157 | + # No event available, check stop signal and continue |
| 158 | + continue |
| 159 | + except Exception as e: |
| 160 | + logger.error(f"Worker {worker_id} unexpected error: {e}") |
| 161 | + |
| 162 | + logger.debug(f"Worker {worker_id} stopped") |
0 commit comments