1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
|
# demonstrations/advanced_patterns/custom_protocols.py
"""
DEMONSTRATION: Custom SSE Protocols
PURPOSE:
Shows how to build custom protocols on top of SSE for specialized use cases.
KEY LEARNING:
- SSE can be extended with custom event types and data formats
- Protocol versioning and negotiation
- Building domain-specific streaming APIs
PATTERN:
Layered protocol design using SSE as transport layer.
"""
import asyncio
import json
from dataclasses import dataclass, asdict
from enum import Enum
from typing import Dict, Any, Optional
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.routing import Route
from sse_starlette import EventSourceResponse, ServerSentEvent
class TaskStatus(Enum):
"""Task execution states in our custom protocol."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class TaskProgressEvent:
"""
Custom protocol message for task progress updates.
This demonstrates structured data over SSE.
"""
task_id: str
status: TaskStatus
progress_percent: int
message: str
timestamp: float
metadata: Optional[Dict[str, Any]] = None
def to_sse_event(self) -> ServerSentEvent:
"""Convert to SSE event with custom protocol structure."""
return ServerSentEvent(
data=json.dumps(asdict(self)),
event="task_progress",
id=f"{self.task_id}-{int(self.timestamp)}",
)
@dataclass
class SystemHealthEvent:
"""Protocol message for system health monitoring."""
component: str
status: str
metrics: Dict[str, float]
alerts: list[str]
timestamp: float
def to_sse_event(self) -> ServerSentEvent:
return ServerSentEvent(
data=json.dumps(asdict(self)),
event="health_update",
id=f"health-{int(self.timestamp)}",
)
class CustomProtocolHandler:
"""
Handles custom protocol logic and message formatting.
Demonstrates how to build domain-specific APIs over SSE.
"""
def __init__(self, protocol_version: str = "1.0"):
self.protocol_version = protocol_version
self.active_tasks: Dict[str, TaskStatus] = {}
self.client_capabilities: Dict[str, set] = {}
def negotiate_protocol(self, request: Request) -> Dict[str, Any]:
"""
Negotiate protocol capabilities with client.
Uses HTTP headers for capability exchange.
"""
client_version = request.headers.get("X-Protocol-Version", "1.0")
client_features = request.headers.get("X-Client-Features", "").split(",")
# Store client capabilities
client_id = str(id(request))
self.client_capabilities[client_id] = set(
f.strip() for f in client_features if f.strip()
)
return {
"server_version": self.protocol_version,
"client_version": client_version,
"supported_events": [
"task_progress",
"health_update",
"system_alert",
"protocol_info",
],
"features": ["compression", "batching", "filtering"],
}
def supports_feature(self, client_id: str, feature: str) -> bool:
"""Check if client supports a specific feature."""
return feature in self.client_capabilities.get(client_id, set())
async def create_protocol_handshake_event(
self, request: Request
) -> ServerSentEvent:
"""
Create initial handshake event with protocol information.
This establishes the custom protocol session.
"""
protocol_info = self.negotiate_protocol(request)
return ServerSentEvent(
data=json.dumps(protocol_info), event="protocol_handshake", id="handshake-0"
)
# Global protocol handler
protocol_handler = CustomProtocolHandler()
async def task_monitoring_protocol(request: Request):
"""
Custom protocol for task monitoring and progress tracking.
Demonstrates structured, domain-specific SSE communication.
"""
client_id = str(id(request))
# Send protocol handshake
yield protocol_handler.create_protocol_handshake_event(request)
# Simulate multiple tasks with different lifecycles
tasks = [
{"id": "build-001", "name": "Build Application", "duration": 8},
{"id": "test-001", "name": "Run Tests", "duration": 5},
{"id": "deploy-001", "name": "Deploy to Production", "duration": 3},
]
import time
try:
for task in tasks:
task_id = task["id"]
duration = task["duration"]
# Task starting
start_event = TaskProgressEvent(
task_id=task_id,
status=TaskStatus.PENDING,
progress_percent=0,
message=f"Starting {task['name']}",
timestamp=time.time(),
)
yield start_event.to_sse_event()
# Task running with progress updates
for progress in range(0, 101, 20):
if await request.is_disconnected():
return
status = TaskStatus.RUNNING if progress < 100 else TaskStatus.COMPLETED
message = f"{task['name']} - {progress}% complete"
progress_event = TaskProgressEvent(
task_id=task_id,
status=status,
progress_percent=progress,
message=message,
timestamp=time.time(),
metadata={"phase": "execution", "worker": f"worker-{task_id[-1]}"},
)
yield progress_event.to_sse_event()
await asyncio.sleep(duration / 5) # Spread progress over task duration
# Brief pause between tasks
await asyncio.sleep(0.5)
except Exception as e:
# Send error in protocol format
error_event = TaskProgressEvent(
task_id="system",
status=TaskStatus.FAILED,
progress_percent=0,
message=f"Protocol error: {e}",
timestamp=time.time(),
)
yield error_event.to_sse_event()
async def system_monitoring_protocol(request: Request):
"""
Custom protocol for system health monitoring.
Shows how to stream complex structured data.
"""
import time
import random
# Send protocol handshake
yield protocol_handler.create_protocol_handshake_event(request)
components = ["database", "cache", "api", "worker"]
try:
for cycle in range(20):
if await request.is_disconnected():
break
# Generate health data for each component
for component in components:
# Simulate varying health metrics
cpu_usage = random.uniform(10, 90)
memory_usage = random.uniform(20, 80)
response_time = random.uniform(50, 500)
# Generate alerts based on thresholds
alerts = []
if cpu_usage > 80:
alerts.append(f"High CPU usage: {cpu_usage:.1f}%")
if memory_usage > 70:
alerts.append(f"High memory usage: {memory_usage:.1f}%")
if response_time > 300:
alerts.append(f"Slow response time: {response_time:.0f}ms")
status = (
"healthy"
if not alerts
else "warning"
if len(alerts) < 2
else "critical"
)
health_event = SystemHealthEvent(
component=component,
status=status,
metrics={
"cpu_usage_percent": cpu_usage,
"memory_usage_percent": memory_usage,
"response_time_ms": response_time,
"uptime_hours": cycle * 0.1,
},
alerts=alerts,
timestamp=time.time(),
)
yield health_event.to_sse_event()
await asyncio.sleep(2) # Health check interval
except Exception as e:
# Send system error
error_event = SystemHealthEvent(
component="monitoring",
status="failed",
metrics={},
alerts=[f"Monitoring system error: {e}"],
timestamp=time.time(),
)
yield error_event.to_sse_event()
async def multi_protocol_endpoint(request: Request):
"""
Endpoint that supports multiple custom protocols based on request parameters.
Demonstrates protocol selection and routing.
"""
protocol_type = request.query_params.get("protocol", "task")
if protocol_type == "task":
return EventSourceResponse(
task_monitoring_protocol(request),
headers={"X-Protocol-Type": "task-monitoring-v1"},
)
elif protocol_type == "health":
return EventSourceResponse(
system_monitoring_protocol(request),
headers={"X-Protocol-Type": "health-monitoring-v1"},
)
else:
# Default: Send protocol information
async def protocol_info():
yield ServerSentEvent(
data=json.dumps(
{
"error": f"Unknown protocol: {protocol_type}",
"available_protocols": ["task", "health"],
"usage": "Add ?protocol=<type> to URL",
}
),
event="protocol_error",
)
return EventSourceResponse(protocol_info())
async def compressed_protocol_endpoint(request: Request):
"""
Demonstrates protocol with data compression and batching.
Advanced technique for high-throughput scenarios.
"""
client_id = str(id(request))
supports_batching = protocol_handler.supports_feature(client_id, "batching")
async def compressed_stream():
# Send handshake
yield protocol_handler.create_protocol_handshake_event(request)
import time
batch_buffer = []
# Generate high-frequency data
for i in range(100):
if await request.is_disconnected():
break
event_data = {
"sequence": i,
"timestamp": time.time(),
"data": f"High frequency data point {i}",
"metrics": {"value": i * 1.5, "rate": i / 10.0},
}
if supports_batching:
# Batch events for efficiency
batch_buffer.append(event_data)
if len(batch_buffer) >= 5: # Batch size
yield ServerSentEvent(
data=json.dumps({"batch": batch_buffer}),
event="data_batch",
id=f"batch-{i // 5}",
)
batch_buffer = []
else:
# Send individual events
yield ServerSentEvent(
data=json.dumps(event_data), event="data_point", id=str(i)
)
await asyncio.sleep(0.1)
# Send any remaining batched data
if batch_buffer:
yield ServerSentEvent(
data=json.dumps({"batch": batch_buffer}),
event="data_batch",
id="final-batch",
)
return EventSourceResponse(compressed_stream())
# Test application
app = Starlette(
routes=[
Route("/protocols", multi_protocol_endpoint),
Route("/compressed", compressed_protocol_endpoint),
]
)
if __name__ == "__main__":
"""
DEMONSTRATION STEPS:
1. Run server: python custom_protocols.py
2. Test task monitoring protocol:
curl -N -H "X-Protocol-Version: 1.0" -H "X-Client-Features: batching,compression" \
"http://localhost:8000/protocols?protocol=task"
3. Test health monitoring protocol:
curl -N "http://localhost:8000/protocols?protocol=health"
4. Test compressed/batched protocol:
curl -N -H "X-Client-Features: batching" \
"http://localhost:8000/compressed"
CUSTOM PROTOCOL BENEFITS:
1. **Structured Communication**:
- Predefined message formats
- Type safety and validation
- Clear contract between client/server
2. **Protocol Negotiation**:
- Version compatibility checking
- Feature capability exchange
- Graceful degradation
3. **Domain-Specific Optimization**:
- Specialized event types
- Efficient data encoding
- Batch operations for performance
4. **Error Handling**:
- Protocol-aware error messages
- Structured error information
- Recovery mechanisms
PRODUCTION PATTERNS:
- Define clear message schemas
- Implement protocol versioning
- Handle capability negotiation
- Optimize for specific use cases
- Document protocol specifications
"""
import uvicorn
print("🚀 Starting custom protocols demonstration server...")
print("📋 Available endpoints:")
print(" /protocols?protocol=task - Task monitoring protocol")
print(" /protocols?protocol=health - Health monitoring protocol")
print(" /compressed - Batching and compression demo")
print("💡 Use X-Protocol-Version and X-Client-Features headers")
uvicorn.run(app, host="localhost", port=8000, log_level="info")
|