askrobots / dbbasic-object-primitive
Public
Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.
events.py · 7.5 KB · 284 lines
| 1 | """ |
| 2 | Events Object - Pub/Sub event system for Object Primitives |
| 3 | |
| 4 | This object provides event publishing and subscription capabilities. |
| 5 | Objects can publish events and subscribe to event types. |
| 6 | |
| 7 | Example usage: |
| 8 | # Publish event |
| 9 | POST /objects/events |
| 10 | { |
| 11 | "event_type": "user.created", |
| 12 | "payload": {"user_id": "123", "username": "alice"}, |
| 13 | "source": "auth" |
| 14 | } |
| 15 | |
| 16 | # Subscribe to event type |
| 17 | GET /objects/events?subscribe=user.created |
| 18 | |
| 19 | # Query event history |
| 20 | GET /objects/events?event_type=user.created&since=1234567890&limit=10 |
| 21 | |
| 22 | # Get all events |
| 23 | GET /objects/events |
| 24 | """ |
| 25 | |
| 26 | import time |
| 27 | import json |
| 28 | import secrets |
| 29 | from typing import Any, Dict, List, Optional |
| 30 | |
| 31 | # These will be injected by ObjectRuntime |
| 32 | _logger = None |
| 33 | _state_manager = None |
| 34 | |
| 35 | |
| 36 | def POST(request: Dict[str, Any]) -> Dict[str, Any]: |
| 37 | """Publish event""" |
| 38 | event_type = request.get('event_type', '').strip() |
| 39 | payload = request.get('payload', {}) |
| 40 | source = request.get('source', 'unknown') |
| 41 | |
| 42 | if not event_type: |
| 43 | return {'status': 'error', 'message': 'event_type is required'} |
| 44 | |
| 45 | # Create event |
| 46 | event_id = secrets.token_hex(8) |
| 47 | timestamp = int(time.time()) |
| 48 | |
| 49 | event = { |
| 50 | 'id': event_id, |
| 51 | 'event_type': event_type, |
| 52 | 'payload': payload, |
| 53 | 'source': source, |
| 54 | 'timestamp': timestamp, |
| 55 | } |
| 56 | |
| 57 | # Save to immutable event log (append-only) |
| 58 | _save_event(event) |
| 59 | |
| 60 | # Notify subscribers (best-effort) |
| 61 | _notify_subscribers(event) |
| 62 | |
| 63 | if _logger: |
| 64 | _logger.info('Event published', |
| 65 | event_id=event_id, |
| 66 | event_type=event_type, |
| 67 | source=source) |
| 68 | |
| 69 | return { |
| 70 | 'status': 'ok', |
| 71 | 'event_id': event_id, |
| 72 | 'timestamp': timestamp, |
| 73 | 'message': f'Event published: {event_type}', |
| 74 | } |
| 75 | |
| 76 | |
| 77 | def GET(request: Dict[str, Any]) -> Dict[str, Any]: |
| 78 | """Query events or subscribe to event type""" |
| 79 | |
| 80 | # Subscribe to event type |
| 81 | subscribe_to = request.get('subscribe') |
| 82 | if subscribe_to: |
| 83 | return _subscribe(subscribe_to, request) |
| 84 | |
| 85 | # Query event history |
| 86 | event_type = request.get('event_type') |
| 87 | since = request.get('since') # Unix timestamp |
| 88 | limit = request.get('limit', 100) |
| 89 | |
| 90 | try: |
| 91 | limit = int(limit) |
| 92 | except (ValueError, TypeError): |
| 93 | limit = 100 |
| 94 | |
| 95 | try: |
| 96 | since = int(since) if since else None |
| 97 | except (ValueError, TypeError): |
| 98 | since = None |
| 99 | |
| 100 | # Get all events |
| 101 | events = _get_all_events() |
| 102 | |
| 103 | # Filter by event_type |
| 104 | if event_type: |
| 105 | events = [e for e in events if e.get('event_type') == event_type] |
| 106 | |
| 107 | # Filter by timestamp (inclusive - events >= since) |
| 108 | if since: |
| 109 | events = [e for e in events if e.get('timestamp', 0) >= since] |
| 110 | |
| 111 | # Apply limit |
| 112 | events = events[:limit] |
| 113 | |
| 114 | return { |
| 115 | 'status': 'ok', |
| 116 | 'events': events, |
| 117 | 'count': len(events), |
| 118 | } |
| 119 | |
| 120 | |
| 121 | def DELETE(request: Dict[str, Any]) -> Dict[str, Any]: |
| 122 | """Unsubscribe from event type""" |
| 123 | event_type = request.get('event_type', '').strip() |
| 124 | subscriber_id = request.get('subscriber_id', '').strip() |
| 125 | |
| 126 | if not event_type: |
| 127 | return {'status': 'error', 'message': 'event_type is required'} |
| 128 | |
| 129 | if not subscriber_id: |
| 130 | return {'status': 'error', 'message': 'subscriber_id is required'} |
| 131 | |
| 132 | # Remove subscription |
| 133 | subscription = _get_subscription(event_type, subscriber_id) |
| 134 | if not subscription: |
| 135 | return {'status': 'error', 'message': 'Subscription not found'} |
| 136 | |
| 137 | _delete_subscription(event_type, subscriber_id) |
| 138 | |
| 139 | if _logger: |
| 140 | _logger.info('Unsubscribed from event', |
| 141 | event_type=event_type, |
| 142 | subscriber_id=subscriber_id) |
| 143 | |
| 144 | return { |
| 145 | 'status': 'ok', |
| 146 | 'message': f'Unsubscribed from {event_type}', |
| 147 | } |
| 148 | |
| 149 | |
| 150 | # Helper functions |
| 151 | |
| 152 | def _subscribe(event_type: str, request: Dict[str, Any]) -> Dict[str, Any]: |
| 153 | """Subscribe to event type""" |
| 154 | subscriber_id = request.get('subscriber_id', secrets.token_hex(8)) |
| 155 | callback_url = request.get('callback_url', '') |
| 156 | |
| 157 | subscription = { |
| 158 | 'id': subscriber_id, |
| 159 | 'event_type': event_type, |
| 160 | 'callback_url': callback_url, |
| 161 | 'created_at': int(time.time()), |
| 162 | 'last_event_id': None, |
| 163 | } |
| 164 | |
| 165 | _save_subscription(subscription) |
| 166 | |
| 167 | if _logger: |
| 168 | _logger.info('Subscribed to event', |
| 169 | event_type=event_type, |
| 170 | subscriber_id=subscriber_id) |
| 171 | |
| 172 | return { |
| 173 | 'status': 'ok', |
| 174 | 'subscriber_id': subscriber_id, |
| 175 | 'event_type': event_type, |
| 176 | 'message': f'Subscribed to {event_type}', |
| 177 | } |
| 178 | |
| 179 | |
| 180 | def _save_event(event: Dict[str, Any]) -> None: |
| 181 | """Save event to immutable log (append-only)""" |
| 182 | if not _state_manager: |
| 183 | return |
| 184 | |
| 185 | event_id = event['id'] |
| 186 | timestamp = event['timestamp'] |
| 187 | |
| 188 | # Store with timestamp prefix for chronological ordering |
| 189 | key = f'event_{timestamp}_{event_id}' |
| 190 | _state_manager.set(key, json.dumps(event)) |
| 191 | |
| 192 | |
| 193 | def _get_all_events() -> List[Dict[str, Any]]: |
| 194 | """Get all events from log""" |
| 195 | if not _state_manager: |
| 196 | return [] |
| 197 | |
| 198 | events = [] |
| 199 | all_state = _state_manager.get_all() |
| 200 | |
| 201 | for key, value in all_state.items(): |
| 202 | if key.startswith('event_'): |
| 203 | event = json.loads(value) |
| 204 | events.append(event) |
| 205 | |
| 206 | # Sort by timestamp (newest first) |
| 207 | events.sort(key=lambda e: e.get('timestamp', 0), reverse=True) |
| 208 | |
| 209 | return events |
| 210 | |
| 211 | |
| 212 | def _save_subscription(subscription: Dict[str, Any]) -> None: |
| 213 | """Save subscription""" |
| 214 | if not _state_manager: |
| 215 | return |
| 216 | |
| 217 | event_type = subscription['event_type'] |
| 218 | subscriber_id = subscription['id'] |
| 219 | |
| 220 | key = f'sub_{event_type}_{subscriber_id}' |
| 221 | _state_manager.set(key, json.dumps(subscription)) |
| 222 | |
| 223 | |
| 224 | def _get_subscription(event_type: str, subscriber_id: str) -> Optional[Dict[str, Any]]: |
| 225 | """Get subscription""" |
| 226 | if not _state_manager: |
| 227 | return None |
| 228 | |
| 229 | key = f'sub_{event_type}_{subscriber_id}' |
| 230 | sub_json = _state_manager.get(key) |
| 231 | |
| 232 | if not sub_json: |
| 233 | return None |
| 234 | |
| 235 | return json.loads(sub_json) |
| 236 | |
| 237 | |
| 238 | def _delete_subscription(event_type: str, subscriber_id: str) -> None: |
| 239 | """Delete subscription""" |
| 240 | if not _state_manager: |
| 241 | return |
| 242 | |
| 243 | key = f'sub_{event_type}_{subscriber_id}' |
| 244 | _state_manager.delete(key) |
| 245 | |
| 246 | |
| 247 | def _get_subscriptions_for_event(event_type: str) -> List[Dict[str, Any]]: |
| 248 | """Get all subscriptions for an event type""" |
| 249 | if not _state_manager: |
| 250 | return [] |
| 251 | |
| 252 | subscriptions = [] |
| 253 | all_state = _state_manager.get_all() |
| 254 | |
| 255 | prefix = f'sub_{event_type}_' |
| 256 | for key, value in all_state.items(): |
| 257 | if key.startswith(prefix): |
| 258 | subscription = json.loads(value) |
| 259 | subscriptions.append(subscription) |
| 260 | |
| 261 | return subscriptions |
| 262 | |
| 263 | |
| 264 | def _notify_subscribers(event: Dict[str, Any]) -> None: |
| 265 | """Notify subscribers of event (best-effort)""" |
| 266 | event_type = event['event_type'] |
| 267 | subscriptions = _get_subscriptions_for_event(event_type) |
| 268 | |
| 269 | for subscription in subscriptions: |
| 270 | callback_url = subscription.get('callback_url') |
| 271 | |
| 272 | if callback_url: |
| 273 | # In a real implementation, this would make HTTP POST to callback_url |
| 274 | # For now, we just log it |
| 275 | if _logger: |
| 276 | _logger.info('Notifying subscriber', |
| 277 | event_id=event['id'], |
| 278 | event_type=event_type, |
| 279 | subscriber_id=subscription['id'], |
| 280 | callback_url=callback_url) |
| 281 | |
| 282 | # Update last_event_id |
| 283 | subscription['last_event_id'] = event['id'] |
| 284 | _save_subscription(subscription) |