Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
dbbasic_event_store.py · 25.9 KB · 703 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | DBBasic Immutable Event Store |
| 4 | ============================== |
| 5 | True event sourcing implementation for DBBasic framework. |
| 6 | All state changes are stored as immutable events that can be replayed. |
| 7 | """ |
| 8 | |
| 9 | import json |
| 10 | import time |
| 11 | import uuid |
| 12 | from datetime import datetime, timezone |
| 13 | from typing import Dict, List, Optional, Any, Callable |
| 14 | from pathlib import Path |
| 15 | import duckdb |
| 16 | import asyncio |
| 17 | |
| 18 | from dbbasic_event_store_presentation import get_event_store_dashboard |
| 19 | from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect |
| 20 | from fastapi.middleware.cors import CORSMiddleware |
| 21 | from fastapi.staticfiles import StaticFiles |
| 22 | from fastapi.responses import HTMLResponse |
| 23 | from pydantic import BaseModel |
| 24 | import uvicorn |
| 25 | import logging |
| 26 | |
| 27 | from presentation_layer import PresentationLayer |
| 28 | from bootstrap_components import ExtendedBootstrapRenderer |
| 29 | from dbbasic_unified_ui import get_master_layout, SERVICES |
| 30 | |
| 31 | # Initialize presentation layer |
| 32 | PresentationLayer.add_renderer('bootstrap', ExtendedBootstrapRenderer()) |
| 33 | |
| 34 | |
| 35 | # Setup logging |
| 36 | logging.basicConfig(level=logging.INFO) |
| 37 | logger = logging.getLogger(__name__) |
| 38 | |
| 39 | # Event Models |
| 40 | class Event(BaseModel): |
| 41 | """Immutable event in the event store""" |
| 42 | event_id: str = None |
| 43 | aggregate_id: str |
| 44 | aggregate_type: str |
| 45 | event_type: str |
| 46 | event_version: int |
| 47 | event_data: Dict[str, Any] |
| 48 | event_metadata: Dict[str, Any] = {} |
| 49 | event_timestamp: str = None |
| 50 | sequence_number: Optional[int] = None |
| 51 | |
| 52 | class EventQuery(BaseModel): |
| 53 | """Query parameters for retrieving events""" |
| 54 | aggregate_id: Optional[str] = None |
| 55 | aggregate_type: Optional[str] = None |
| 56 | event_type: Optional[str] = None |
| 57 | from_sequence: Optional[int] = None |
| 58 | to_sequence: Optional[int] = None |
| 59 | from_timestamp: Optional[str] = None |
| 60 | to_timestamp: Optional[str] = None |
| 61 | limit: int = 100 |
| 62 | |
| 63 | class Snapshot(BaseModel): |
| 64 | """Snapshot of aggregate state at a point in time""" |
| 65 | aggregate_id: str |
| 66 | aggregate_type: str |
| 67 | snapshot_version: int |
| 68 | snapshot_data: Dict[str, Any] |
| 69 | snapshot_timestamp: str = None |
| 70 | |
| 71 | class EventStore: |
| 72 | """ |
| 73 | Immutable Event Store implementation using DuckDB |
| 74 | """ |
| 75 | |
| 76 | def __init__(self, database_path: str = "event_store.db"): |
| 77 | self.database_path = database_path |
| 78 | self.conn = duckdb.connect(database_path) |
| 79 | self._init_tables() |
| 80 | self.projections: Dict[str, Callable] = {} |
| 81 | self.event_handlers: List[Callable] = [] |
| 82 | |
| 83 | def _init_tables(self): |
| 84 | """Initialize event store tables""" |
| 85 | # Events table - immutable, append-only |
| 86 | self.conn.execute(""" |
| 87 | CREATE TABLE IF NOT EXISTS events ( |
| 88 | sequence_number BIGINT PRIMARY KEY, |
| 89 | event_id VARCHAR NOT NULL UNIQUE, |
| 90 | aggregate_id VARCHAR NOT NULL, |
| 91 | aggregate_type VARCHAR NOT NULL, |
| 92 | event_type VARCHAR NOT NULL, |
| 93 | event_version INTEGER NOT NULL, |
| 94 | event_data JSON NOT NULL, |
| 95 | event_metadata JSON, |
| 96 | event_timestamp TIMESTAMP NOT NULL |
| 97 | ) |
| 98 | """) |
| 99 | |
| 100 | # Snapshots table - for performance optimization |
| 101 | self.conn.execute(""" |
| 102 | CREATE TABLE IF NOT EXISTS snapshots ( |
| 103 | aggregate_id VARCHAR NOT NULL, |
| 104 | aggregate_type VARCHAR NOT NULL, |
| 105 | snapshot_version INTEGER NOT NULL, |
| 106 | snapshot_data JSON NOT NULL, |
| 107 | snapshot_timestamp TIMESTAMP NOT NULL, |
| 108 | |
| 109 | PRIMARY KEY (aggregate_id, snapshot_version) |
| 110 | ) |
| 111 | """) |
| 112 | |
| 113 | # Create indexes separately for DuckDB |
| 114 | self.conn.execute("CREATE INDEX IF NOT EXISTS idx_aggregate ON events (aggregate_id, event_version)") |
| 115 | self.conn.execute("CREATE INDEX IF NOT EXISTS idx_type ON events (aggregate_type, event_type)") |
| 116 | self.conn.execute("CREATE INDEX IF NOT EXISTS idx_timestamp ON events (event_timestamp)") |
| 117 | self.conn.execute("CREATE INDEX IF NOT EXISTS idx_aggregate_snapshot ON snapshots (aggregate_id, snapshot_version DESC)") |
| 118 | |
| 119 | # Projections table - materialized views |
| 120 | self.conn.execute(""" |
| 121 | CREATE TABLE IF NOT EXISTS projections ( |
| 122 | projection_name VARCHAR NOT NULL, |
| 123 | projection_key VARCHAR NOT NULL, |
| 124 | projection_data JSON NOT NULL, |
| 125 | last_sequence BIGINT NOT NULL, |
| 126 | updated_at TIMESTAMP NOT NULL, |
| 127 | |
| 128 | PRIMARY KEY (projection_name, projection_key) |
| 129 | ) |
| 130 | """) |
| 131 | |
| 132 | logger.info("✅ Event store tables initialized") |
| 133 | |
| 134 | def append_event(self, event: Event) -> int: |
| 135 | """ |
| 136 | Append an event to the event store (immutable operation) |
| 137 | Returns the sequence number of the stored event |
| 138 | """ |
| 139 | # Generate IDs and timestamps if not provided |
| 140 | if not event.event_id: |
| 141 | event.event_id = str(uuid.uuid4()) |
| 142 | if not event.event_timestamp: |
| 143 | event.event_timestamp = datetime.now(timezone.utc).isoformat() |
| 144 | |
| 145 | # Get next sequence number (atomic operation) |
| 146 | result = self.conn.execute(""" |
| 147 | SELECT COALESCE(MAX(sequence_number), 0) + 1 as next_seq |
| 148 | FROM events |
| 149 | """).fetchone() |
| 150 | |
| 151 | sequence_number = result[0] |
| 152 | |
| 153 | # Get current version for this aggregate |
| 154 | version_result = self.conn.execute(""" |
| 155 | SELECT COALESCE(MAX(event_version), 0) as current_version |
| 156 | FROM events |
| 157 | WHERE aggregate_id = ? |
| 158 | """, [event.aggregate_id]).fetchone() |
| 159 | |
| 160 | event.event_version = version_result[0] + 1 |
| 161 | |
| 162 | # Insert the event (immutable) |
| 163 | self.conn.execute(""" |
| 164 | INSERT INTO events ( |
| 165 | sequence_number, event_id, aggregate_id, aggregate_type, |
| 166 | event_type, event_version, event_data, event_metadata, event_timestamp |
| 167 | ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) |
| 168 | """, [ |
| 169 | sequence_number, |
| 170 | event.event_id, |
| 171 | event.aggregate_id, |
| 172 | event.aggregate_type, |
| 173 | event.event_type, |
| 174 | event.event_version, |
| 175 | json.dumps(event.event_data), |
| 176 | json.dumps(event.event_metadata), |
| 177 | event.event_timestamp |
| 178 | ]) |
| 179 | |
| 180 | # Notify event handlers |
| 181 | event.sequence_number = sequence_number |
| 182 | asyncio.create_task(self._notify_handlers(event)) |
| 183 | |
| 184 | # Update projections |
| 185 | asyncio.create_task(self._update_projections(event)) |
| 186 | |
| 187 | logger.info(f"📝 Event stored: {event.event_type} for {event.aggregate_type}:{event.aggregate_id} (seq: {sequence_number})") |
| 188 | return sequence_number |
| 189 | |
| 190 | async def _notify_handlers(self, event: Event): |
| 191 | """Notify all registered event handlers""" |
| 192 | for handler in self.event_handlers: |
| 193 | try: |
| 194 | if asyncio.iscoroutinefunction(handler): |
| 195 | await handler(event) |
| 196 | else: |
| 197 | handler(event) |
| 198 | except Exception as e: |
| 199 | logger.error(f"Error in event handler: {e}") |
| 200 | |
| 201 | async def _update_projections(self, event: Event): |
| 202 | """Update registered projections based on the event""" |
| 203 | for name, projection_func in self.projections.items(): |
| 204 | try: |
| 205 | if asyncio.iscoroutinefunction(projection_func): |
| 206 | projection_data = await projection_func(event) |
| 207 | else: |
| 208 | projection_data = projection_func(event) |
| 209 | |
| 210 | if projection_data: |
| 211 | self._save_projection(name, projection_data, event.sequence_number) |
| 212 | except Exception as e: |
| 213 | logger.error(f"Error updating projection {name}: {e}") |
| 214 | |
| 215 | def _save_projection(self, name: str, data: Dict[str, Any], sequence: int): |
| 216 | """Save projection data""" |
| 217 | for key, value in data.items(): |
| 218 | self.conn.execute(""" |
| 219 | INSERT OR REPLACE INTO projections |
| 220 | (projection_name, projection_key, projection_data, last_sequence, updated_at) |
| 221 | VALUES (?, ?, ?, ?, ?) |
| 222 | """, [ |
| 223 | name, key, json.dumps(value), sequence, |
| 224 | datetime.now(timezone.utc).isoformat() |
| 225 | ]) |
| 226 | |
| 227 | def get_events(self, query: EventQuery) -> List[Event]: |
| 228 | """ |
| 229 | Query events from the store |
| 230 | Events are immutable - this only reads |
| 231 | """ |
| 232 | sql = "SELECT * FROM events WHERE 1=1" |
| 233 | params = [] |
| 234 | |
| 235 | if query.aggregate_id: |
| 236 | sql += " AND aggregate_id = ?" |
| 237 | params.append(query.aggregate_id) |
| 238 | |
| 239 | if query.aggregate_type: |
| 240 | sql += " AND aggregate_type = ?" |
| 241 | params.append(query.aggregate_type) |
| 242 | |
| 243 | if query.event_type: |
| 244 | sql += " AND event_type = ?" |
| 245 | params.append(query.event_type) |
| 246 | |
| 247 | if query.from_sequence: |
| 248 | sql += " AND sequence_number >= ?" |
| 249 | params.append(query.from_sequence) |
| 250 | |
| 251 | if query.to_sequence: |
| 252 | sql += " AND sequence_number <= ?" |
| 253 | params.append(query.to_sequence) |
| 254 | |
| 255 | if query.from_timestamp: |
| 256 | sql += " AND event_timestamp >= ?" |
| 257 | params.append(query.from_timestamp) |
| 258 | |
| 259 | if query.to_timestamp: |
| 260 | sql += " AND event_timestamp <= ?" |
| 261 | params.append(query.to_timestamp) |
| 262 | |
| 263 | sql += f" ORDER BY sequence_number LIMIT {query.limit}" |
| 264 | |
| 265 | results = self.conn.execute(sql, params).fetchall() |
| 266 | |
| 267 | events = [] |
| 268 | for row in results: |
| 269 | events.append(Event( |
| 270 | sequence_number=row[0], |
| 271 | event_id=row[1], |
| 272 | aggregate_id=row[2], |
| 273 | aggregate_type=row[3], |
| 274 | event_type=row[4], |
| 275 | event_version=row[5], |
| 276 | event_data=json.loads(row[6]), |
| 277 | event_metadata=json.loads(row[7]) if row[7] else {}, |
| 278 | event_timestamp=row[8] |
| 279 | )) |
| 280 | |
| 281 | return events |
| 282 | |
| 283 | def get_aggregate_events(self, aggregate_id: str, from_version: int = 0) -> List[Event]: |
| 284 | """Get all events for a specific aggregate""" |
| 285 | query = EventQuery( |
| 286 | aggregate_id=aggregate_id, |
| 287 | limit=10000 # Get all events for the aggregate |
| 288 | ) |
| 289 | events = self.get_events(query) |
| 290 | return [e for e in events if e.event_version > from_version] |
| 291 | |
| 292 | def rebuild_aggregate(self, aggregate_id: str, aggregate_type: str, |
| 293 | reducer: Callable) -> Dict[str, Any]: |
| 294 | """ |
| 295 | Rebuild aggregate state by replaying all events |
| 296 | This demonstrates the power of event sourcing |
| 297 | """ |
| 298 | # Try to get latest snapshot |
| 299 | snapshot = self.get_latest_snapshot(aggregate_id) |
| 300 | |
| 301 | if snapshot: |
| 302 | state = snapshot.snapshot_data |
| 303 | from_version = snapshot.snapshot_version |
| 304 | else: |
| 305 | state = {} |
| 306 | from_version = 0 |
| 307 | |
| 308 | # Get events after snapshot |
| 309 | events = self.get_aggregate_events(aggregate_id, from_version) |
| 310 | |
| 311 | # Replay events through reducer |
| 312 | for event in events: |
| 313 | state = reducer(state, event) |
| 314 | |
| 315 | return state |
| 316 | |
| 317 | def save_snapshot(self, snapshot: Snapshot): |
| 318 | """Save a snapshot for performance optimization""" |
| 319 | if not snapshot.snapshot_timestamp: |
| 320 | snapshot.snapshot_timestamp = datetime.now(timezone.utc).isoformat() |
| 321 | |
| 322 | self.conn.execute(""" |
| 323 | INSERT INTO snapshots |
| 324 | (aggregate_id, aggregate_type, snapshot_version, snapshot_data, snapshot_timestamp) |
| 325 | VALUES (?, ?, ?, ?, ?) |
| 326 | """, [ |
| 327 | snapshot.aggregate_id, |
| 328 | snapshot.aggregate_type, |
| 329 | snapshot.snapshot_version, |
| 330 | json.dumps(snapshot.snapshot_data), |
| 331 | snapshot.snapshot_timestamp |
| 332 | ]) |
| 333 | |
| 334 | logger.info(f"📸 Snapshot saved for {snapshot.aggregate_type}:{snapshot.aggregate_id} at version {snapshot.snapshot_version}") |
| 335 | |
| 336 | def get_latest_snapshot(self, aggregate_id: str) -> Optional[Snapshot]: |
| 337 | """Get the latest snapshot for an aggregate""" |
| 338 | result = self.conn.execute(""" |
| 339 | SELECT * FROM snapshots |
| 340 | WHERE aggregate_id = ? |
| 341 | ORDER BY snapshot_version DESC |
| 342 | LIMIT 1 |
| 343 | """, [aggregate_id]).fetchone() |
| 344 | |
| 345 | if result: |
| 346 | return Snapshot( |
| 347 | aggregate_id=result[0], |
| 348 | aggregate_type=result[1], |
| 349 | snapshot_version=result[2], |
| 350 | snapshot_data=json.loads(result[3]), |
| 351 | snapshot_timestamp=result[4] |
| 352 | ) |
| 353 | return None |
| 354 | |
| 355 | def register_projection(self, name: str, projection_func: Callable): |
| 356 | """Register a projection function""" |
| 357 | self.projections[name] = projection_func |
| 358 | logger.info(f"📊 Registered projection: {name}") |
| 359 | |
| 360 | def register_event_handler(self, handler: Callable): |
| 361 | """Register an event handler""" |
| 362 | self.event_handlers.append(handler) |
| 363 | logger.info(f"🎯 Registered event handler") |
| 364 | |
| 365 | def get_projection(self, name: str, key: str) -> Optional[Dict[str, Any]]: |
| 366 | """Get projection data""" |
| 367 | result = self.conn.execute(""" |
| 368 | SELECT projection_data FROM projections |
| 369 | WHERE projection_name = ? AND projection_key = ? |
| 370 | """, [name, key]).fetchone() |
| 371 | |
| 372 | if result: |
| 373 | return json.loads(result[0]) |
| 374 | return None |
| 375 | |
| 376 | # FastAPI Application |
| 377 | app = FastAPI(title="DBBasic Event Store") |
| 378 | |
| 379 | # CORS middleware |
| 380 | app.add_middleware( |
| 381 | CORSMiddleware, |
| 382 | allow_origins=["*"], |
| 383 | allow_credentials=True, |
| 384 | allow_methods=["*"], |
| 385 | allow_headers=["*"], |
| 386 | ) |
| 387 | |
| 388 | # Initialize event store |
| 389 | event_store = EventStore() |
| 390 | |
| 391 | # WebSocket connections |
| 392 | websocket_connections: List[WebSocket] = [] |
| 393 | |
| 394 | # API Endpoints |
| 395 | @app.post("/events") |
| 396 | async def append_event(event: Event): |
| 397 | """Append an event to the event store""" |
| 398 | try: |
| 399 | sequence_number = event_store.append_event(event) |
| 400 | |
| 401 | # Broadcast to WebSocket clients |
| 402 | await broadcast_event(event) |
| 403 | |
| 404 | return { |
| 405 | "status": "success", |
| 406 | "sequence_number": sequence_number, |
| 407 | "event_id": event.event_id |
| 408 | } |
| 409 | except Exception as e: |
| 410 | logger.error(f"Error appending event: {e}") |
| 411 | raise HTTPException(status_code=500, detail=str(e)) |
| 412 | |
| 413 | @app.post("/events/query") |
| 414 | async def query_events(query: EventQuery): |
| 415 | """Query events from the store""" |
| 416 | try: |
| 417 | events = event_store.get_events(query) |
| 418 | return { |
| 419 | "events": [e.dict() for e in events], |
| 420 | "count": len(events) |
| 421 | } |
| 422 | except Exception as e: |
| 423 | logger.error(f"Error querying events: {e}") |
| 424 | raise HTTPException(status_code=500, detail=str(e)) |
| 425 | |
| 426 | @app.get("/aggregates/{aggregate_id}") |
| 427 | async def get_aggregate(aggregate_id: str): |
| 428 | """Get all events for an aggregate""" |
| 429 | try: |
| 430 | events = event_store.get_aggregate_events(aggregate_id) |
| 431 | return { |
| 432 | "aggregate_id": aggregate_id, |
| 433 | "events": [e.dict() for e in events], |
| 434 | "version": events[-1].event_version if events else 0 |
| 435 | } |
| 436 | except Exception as e: |
| 437 | logger.error(f"Error getting aggregate: {e}") |
| 438 | raise HTTPException(status_code=500, detail=str(e)) |
| 439 | |
| 440 | @app.post("/snapshots") |
| 441 | async def save_snapshot(snapshot: Snapshot): |
| 442 | """Save a snapshot""" |
| 443 | try: |
| 444 | event_store.save_snapshot(snapshot) |
| 445 | return {"status": "success"} |
| 446 | except Exception as e: |
| 447 | logger.error(f"Error saving snapshot: {e}") |
| 448 | raise HTTPException(status_code=500, detail=str(e)) |
| 449 | |
| 450 | @app.get("/projections/{name}/{key}") |
| 451 | async def get_projection(name: str, key: str): |
| 452 | """Get projection data""" |
| 453 | try: |
| 454 | data = event_store.get_projection(name, key) |
| 455 | if data: |
| 456 | return data |
| 457 | raise HTTPException(status_code=404, detail="Projection not found") |
| 458 | except Exception as e: |
| 459 | logger.error(f"Error getting projection: {e}") |
| 460 | raise HTTPException(status_code=500, detail=str(e)) |
| 461 | |
| 462 | @app.websocket("/ws") |
| 463 | async def websocket_endpoint(websocket: WebSocket): |
| 464 | """WebSocket for real-time event streaming""" |
| 465 | await websocket.accept() |
| 466 | websocket_connections.append(websocket) |
| 467 | try: |
| 468 | while True: |
| 469 | await websocket.receive_text() |
| 470 | except WebSocketDisconnect: |
| 471 | websocket_connections.remove(websocket) |
| 472 | |
| 473 | async def broadcast_event(event: Event): |
| 474 | """Broadcast event to all WebSocket clients""" |
| 475 | for connection in websocket_connections: |
| 476 | try: |
| 477 | await connection.send_json(event.dict()) |
| 478 | except: |
| 479 | websocket_connections.remove(connection) |
| 480 | |
| 481 | # Web Interface |
| 482 | @app.get("/", response_class=HTMLResponse) |
| 483 | async def get_interface(): |
| 484 | """Serve the event store web interface""" |
| 485 | return """ |
| 486 | <!DOCTYPE html> |
| 487 | <html> |
| 488 | <head> |
| 489 | <title>DBBasic Event Store</title> |
| 490 | <style> |
| 491 | * { margin: 0; padding: 0; box-sizing: border-box; } |
| 492 | body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); } |
| 493 | .container { max-width: 1400px; margin: 0 auto; padding: 2rem; } |
| 494 | h1 { color: white; margin-bottom: 2rem; font-size: 2.5rem; } |
| 495 | .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; } |
| 496 | .card { background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 10px 30px rgba(0,0,0,0.2); } |
| 497 | h2 { color: #2c3e50; margin-bottom: 1rem; font-size: 1.5rem; } |
| 498 | .form-group { margin-bottom: 1rem; } |
| 499 | label { display: block; margin-bottom: 0.5rem; color: #555; font-weight: 500; } |
| 500 | input, select, textarea { width: 100%; padding: 0.75rem; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 1rem; } |
| 501 | input:focus, select:focus, textarea:focus { border-color: #667eea; outline: none; } |
| 502 | button { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 0.75rem 1.5rem; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; font-weight: 600; } |
| 503 | button:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); } |
| 504 | .event-list { max-height: 400px; overflow-y: auto; border: 2px solid #e0e0e0; border-radius: 8px; padding: 1rem; background: #f9f9f9; } |
| 505 | .event-item { padding: 0.75rem; margin-bottom: 0.5rem; background: white; border-radius: 8px; border-left: 4px solid #667eea; } |
| 506 | .event-header { display: flex; justify-content: space-between; margin-bottom: 0.5rem; } |
| 507 | .event-type { font-weight: 600; color: #2c3e50; } |
| 508 | .event-time { color: #888; font-size: 0.9rem; } |
| 509 | .event-data { font-family: 'Courier New', monospace; font-size: 0.9rem; color: #555; background: #f5f5f5; padding: 0.5rem; border-radius: 4px; margin-top: 0.5rem; } |
| 510 | .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; margin-top: 2rem; } |
| 511 | .stat-card { background: white; padding: 1.5rem; border-radius: 12px; text-align: center; box-shadow: 0 5px 15px rgba(0,0,0,0.1); } |
| 512 | .stat-value { font-size: 2rem; font-weight: bold; color: #667eea; } |
| 513 | .stat-label { color: #888; margin-top: 0.5rem; } |
| 514 | .status { padding: 0.25rem 0.5rem; border-radius: 20px; font-size: 0.8rem; font-weight: 600; } |
| 515 | .status.connected { background: #4CAF50; color: white; } |
| 516 | .status.disconnected { background: #f44336; color: white; } |
| 517 | </style> |
| 518 | </head> |
| 519 | <body> |
| 520 | <div class="container"> |
| 521 | <h1>🗄️ DBBasic Event Store <span id="status" class="status disconnected">Disconnected</span></h1> |
| 522 | |
| 523 | <div class="grid"> |
| 524 | <div class="card"> |
| 525 | <h2>📝 Append Event</h2> |
| 526 | <form id="eventForm"> |
| 527 | <div class="form-group"> |
| 528 | <label>Aggregate ID</label> |
| 529 | <input type="text" id="aggregateId" placeholder="e.g., user-123" required> |
| 530 | </div> |
| 531 | <div class="form-group"> |
| 532 | <label>Aggregate Type</label> |
| 533 | <input type="text" id="aggregateType" placeholder="e.g., User" required> |
| 534 | </div> |
| 535 | <div class="form-group"> |
| 536 | <label>Event Type</label> |
| 537 | <input type="text" id="eventType" placeholder="e.g., UserCreated" required> |
| 538 | </div> |
| 539 | <div class="form-group"> |
| 540 | <label>Event Data (JSON)</label> |
| 541 | <textarea id="eventData" rows="4" placeholder='{"name": "John Doe", "email": "john@example.com"}' required></textarea> |
| 542 | </div> |
| 543 | <button type="submit">Append Event</button> |
| 544 | </form> |
| 545 | </div> |
| 546 | |
| 547 | <div class="card"> |
| 548 | <h2>📊 Recent Events</h2> |
| 549 | <div id="eventList" class="event-list"> |
| 550 | <p style="color: #888;">No events yet...</p> |
| 551 | </div> |
| 552 | </div> |
| 553 | </div> |
| 554 | |
| 555 | <div class="stats" id="stats"> |
| 556 | <div class="stat-card"> |
| 557 | <div class="stat-value" id="totalEvents">0</div> |
| 558 | <div class="stat-label">Total Events</div> |
| 559 | </div> |
| 560 | <div class="stat-card"> |
| 561 | <div class="stat-value" id="aggregateCount">0</div> |
| 562 | <div class="stat-label">Aggregates</div> |
| 563 | </div> |
| 564 | <div class="stat-card"> |
| 565 | <div class="stat-value" id="eventsPerSec">0</div> |
| 566 | <div class="stat-label">Events/sec</div> |
| 567 | </div> |
| 568 | </div> |
| 569 | </div> |
| 570 | |
| 571 | <script> |
| 572 | let ws = null; |
| 573 | let eventCount = 0; |
| 574 | let aggregates = new Set(); |
| 575 | let eventsInLastSecond = 0; |
| 576 | |
| 577 | function connectWebSocket() { |
| 578 | ws = new WebSocket('ws://localhost:8007/ws'); |
| 579 | |
| 580 | ws.onopen = () => { |
| 581 | document.getElementById('status').textContent = 'Connected'; |
| 582 | document.getElementById('status').className = 'status connected'; |
| 583 | }; |
| 584 | |
| 585 | ws.onmessage = (event) => { |
| 586 | const data = JSON.parse(event.data); |
| 587 | addEventToList(data); |
| 588 | updateStats(data); |
| 589 | }; |
| 590 | |
| 591 | ws.onclose = () => { |
| 592 | document.getElementById('status').textContent = 'Disconnected'; |
| 593 | document.getElementById('status').className = 'status disconnected'; |
| 594 | setTimeout(connectWebSocket, 3000); |
| 595 | }; |
| 596 | } |
| 597 | |
| 598 | function addEventToList(event) { |
| 599 | const list = document.getElementById('eventList'); |
| 600 | if (list.querySelector('p')) { |
| 601 | list.innerHTML = ''; |
| 602 | } |
| 603 | |
| 604 | const eventItem = document.createElement('div'); |
| 605 | eventItem.className = 'event-item'; |
| 606 | eventItem.innerHTML = ` |
| 607 | <div class="event-header"> |
| 608 | <span class="event-type">${event.event_type}</span> |
| 609 | <span class="event-time">${new Date(event.event_timestamp).toLocaleTimeString()}</span> |
| 610 | </div> |
| 611 | <div>Aggregate: ${event.aggregate_type}:${event.aggregate_id}</div> |
| 612 | <div>Version: ${event.event_version} | Sequence: ${event.sequence_number}</div> |
| 613 | <div class="event-data">${JSON.stringify(event.event_data, null, 2)}</div> |
| 614 | `; |
| 615 | |
| 616 | list.insertBefore(eventItem, list.firstChild); |
| 617 | |
| 618 | // Keep only last 10 events |
| 619 | while (list.children.length > 10) { |
| 620 | list.removeChild(list.lastChild); |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | function updateStats(event) { |
| 625 | eventCount++; |
| 626 | aggregates.add(event.aggregate_id); |
| 627 | eventsInLastSecond++; |
| 628 | |
| 629 | document.getElementById('totalEvents').textContent = eventCount; |
| 630 | document.getElementById('aggregateCount').textContent = aggregates.size; |
| 631 | |
| 632 | setTimeout(() => { |
| 633 | eventsInLastSecond--; |
| 634 | document.getElementById('eventsPerSec').textContent = eventsInLastSecond; |
| 635 | }, 1000); |
| 636 | |
| 637 | document.getElementById('eventsPerSec').textContent = eventsInLastSecond; |
| 638 | } |
| 639 | |
| 640 | document.getElementById('eventForm').addEventListener('submit', async (e) => { |
| 641 | e.preventDefault(); |
| 642 | |
| 643 | const event = { |
| 644 | aggregate_id: document.getElementById('aggregateId').value, |
| 645 | aggregate_type: document.getElementById('aggregateType').value, |
| 646 | event_type: document.getElementById('eventType').value, |
| 647 | event_data: JSON.parse(document.getElementById('eventData').value) |
| 648 | }; |
| 649 | |
| 650 | try { |
| 651 | const response = await fetch('/events', { |
| 652 | method: 'POST', |
| 653 | headers: { 'Content-Type': 'application/json' }, |
| 654 | body: JSON.stringify(event) |
| 655 | }); |
| 656 | |
| 657 | if (response.ok) { |
| 658 | document.getElementById('eventForm').reset(); |
| 659 | document.getElementById('eventData').value = '{}'; |
| 660 | } else { |
| 661 | alert('Error appending event'); |
| 662 | } |
| 663 | } catch (error) { |
| 664 | alert('Error: ' + error.message); |
| 665 | } |
| 666 | }); |
| 667 | |
| 668 | // Load initial stats |
| 669 | async function loadStats() { |
| 670 | try { |
| 671 | const response = await fetch('/events/query', { |
| 672 | method: 'POST', |
| 673 | headers: { 'Content-Type': 'application/json' }, |
| 674 | body: JSON.stringify({ limit: 1000 }) |
| 675 | }); |
| 676 | |
| 677 | if (response.ok) { |
| 678 | const data = await response.json(); |
| 679 | eventCount = data.count; |
| 680 | |
| 681 | data.events.forEach(event => { |
| 682 | aggregates.add(event.aggregate_id); |
| 683 | addEventToList(event); |
| 684 | }); |
| 685 | |
| 686 | document.getElementById('totalEvents').textContent = eventCount; |
| 687 | document.getElementById('aggregateCount').textContent = aggregates.size; |
| 688 | } |
| 689 | } catch (error) { |
| 690 | console.error('Error loading stats:', error); |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | connectWebSocket(); |
| 695 | loadStats(); |
| 696 | </script> |
| 697 | </body> |
| 698 | </html> |
| 699 | """ |
| 700 | |
| 701 | if __name__ == "__main__": |
| 702 | logger.info("🚀 Starting DBBasic Event Store on http://localhost:8007") |
| 703 | uvicorn.run(app, host="0.0.0.0", port=8007) |