|
| 1 | +from typing import Dict, List |
| 2 | +from src.common.models import DriverLocationEvent |
| 3 | +from src.common.utils import get_logger |
| 4 | + |
| 5 | +logger = get_logger("DriverLocationStore") |
| 6 | + |
| 7 | + |
| 8 | +class DriverLocationStore: |
| 9 | + """ |
| 10 | + In-memory real-time driver store. |
| 11 | +
|
| 12 | + Responsibilities: |
| 13 | + - Maintain driver availability |
| 14 | + - Update driver coordinates |
| 15 | + - Remove offline drivers |
| 16 | + - Provide list of active drivers for Dispatch Service |
| 17 | +
|
| 18 | + This version is intentionally simple, but the interface allows |
| 19 | + easy migration to Redis, MongoDB, or a geospatial index (H3). |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + # driver_id → DriverLocationEvent |
| 24 | + self.drivers: Dict[str, DriverLocationEvent] = {} |
| 25 | + |
| 26 | + # ------------------------------------------------------------ |
| 27 | + # Core Operations |
| 28 | + # ------------------------------------------------------------ |
| 29 | + |
| 30 | + def upsert_driver(self, event: DriverLocationEvent): |
| 31 | + """ |
| 32 | + Add or update driver in the store. |
| 33 | + """ |
| 34 | + self.drivers[event.driver_id] = event |
| 35 | + logger.info(f"Updated driver {event.driver_id} at ({event.lat}, {event.lon})") |
| 36 | + |
| 37 | + def remove_driver(self, driver_id: str): |
| 38 | + """ |
| 39 | + Remove a driver from the store. |
| 40 | + """ |
| 41 | + if driver_id in self.drivers: |
| 42 | + del self.drivers[driver_id] |
| 43 | + logger.info(f"Removed driver {driver_id}") |
| 44 | + |
| 45 | + # ------------------------------------------------------------ |
| 46 | + # Retrieval |
| 47 | + # ------------------------------------------------------------ |
| 48 | + |
| 49 | + def get_all_drivers(self) -> List[DriverLocationEvent]: |
| 50 | + """ |
| 51 | + Return a list of all active drivers. |
| 52 | + """ |
| 53 | + return list(self.drivers.values()) |
| 54 | + |
| 55 | + def get_driver(self, driver_id: str) -> DriverLocationEvent: |
| 56 | + """ |
| 57 | + Fetch a single driver by ID. |
| 58 | + """ |
| 59 | + return self.drivers.get(driver_id) |
| 60 | + |
| 61 | + # ------------------------------------------------------------ |
| 62 | + # Debug Utilities |
| 63 | + # ------------------------------------------------------------ |
| 64 | + |
| 65 | + def count(self) -> int: |
| 66 | + """ |
| 67 | + Count active drivers. |
| 68 | + """ |
| 69 | + return len(self.drivers) |
| 70 | + |
| 71 | + def clear(self): |
| 72 | + """ |
| 73 | + Remove all drivers (reset state). |
| 74 | + """ |
| 75 | + self.drivers.clear() |
| 76 | + logger.warning("Cleared all driver locations.") |
0 commit comments