async-task-worker 0.3.1__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/PKG-INFO +464 -1
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/README.md +463 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/pyproject.toml +2 -2
- async_task_worker-0.4.0/src/async_events/__init__.py +22 -0
- async_task_worker-0.4.0/src/async_events/event_manager.py +284 -0
- async_task_worker-0.4.0/src/async_events/sse_client.py +222 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/core.py +9 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/uv.lock +161 -161
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/.gitignore +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/CLAUDE.md +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/LICENSE +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/__init__.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/adapters/__init__.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/adapters/memory.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/adapters/redis.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/core.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/exceptions.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/key_utils.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_cache/serialization.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/__init__.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/adapters/__init__.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/adapters/cache_adapter.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/api.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/exceptions.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/executor.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/futures.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/pool.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/queue.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/registry.py +0 -0
- {async_task_worker-0.3.1 → async_task_worker-0.4.0}/src/async_task_worker/status.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: async-task-worker
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Async Test Worker
|
|
5
5
|
Project-URL: Homepage, https://github.com/descoped/async-task-worker
|
|
6
6
|
Project-URL: Repository, https://github.com/descoped/async-task-worker
|
|
@@ -45,6 +45,7 @@ pip install async-task-worker
|
|
|
45
45
|
- **API Integration**: Ready-to-use FastAPI router for task management
|
|
46
46
|
- **Modular Structure**: Clean, consistent module organization with a logical structure
|
|
47
47
|
|
|
48
|
+
|
|
48
49
|
## Sequence Diagrams
|
|
49
50
|
|
|
50
51
|
- [Task Registry Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Registry%20Sequence%20Diagram.mmd)
|
|
@@ -52,6 +53,7 @@ pip install async-task-worker
|
|
|
52
53
|
- [Task Cache Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Cache%20Sequence%20Diagram.mmd)
|
|
53
54
|
- [Task Worker API Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/Task%20Worker%20API%20Sequence%20Diagram.mmd)
|
|
54
55
|
- [AsyncTaskWorker Class Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/AsyncTaskWorker%20Class%20Diagram.mmd)
|
|
56
|
+
- [EventManager Sequence Diagram](https://github.com/descoped/async-task-worker/blob/master/docs/EventManager%20Sequence%20Diagram.mmd)
|
|
55
57
|
|
|
56
58
|
|
|
57
59
|
## How It Works
|
|
@@ -1154,6 +1156,467 @@ async def get_cached_result(task_worker, func_name, task_id):
|
|
|
1154
1156
|
return await handle_task_not_in_cache(task_worker, task_id)
|
|
1155
1157
|
```
|
|
1156
1158
|
|
|
1159
|
+
## Event System Integration
|
|
1160
|
+
|
|
1161
|
+
The async_task_worker library can be integrated with the `async_events` package to create a reactive system where task state changes publish events that can be consumed by subscribers. This enables building event-driven architectures with real-time notifications and monitoring.
|
|
1162
|
+
|
|
1163
|
+
### Features
|
|
1164
|
+
|
|
1165
|
+
- **Event-driven Architecture**: Task state changes generate events that subscribers can react to
|
|
1166
|
+
- **Real-time Notifications**: Get immediate updates when tasks change state
|
|
1167
|
+
- **Filtered Event Streams**: Subscribe to events for specific task groups
|
|
1168
|
+
- **Historical Event Access**: Query recent events even after they occurred
|
|
1169
|
+
- **Server-Sent Events Support**: Compatible with SSE for web client integration
|
|
1170
|
+
|
|
1171
|
+
### Getting Started with Events
|
|
1172
|
+
|
|
1173
|
+
```python
|
|
1174
|
+
import asyncio
|
|
1175
|
+
from async_task_worker import AsyncTaskWorker, task
|
|
1176
|
+
from async_events import EventManager, GroupFilter, EventSubscription
|
|
1177
|
+
|
|
1178
|
+
# Global event manager instance
|
|
1179
|
+
event_manager = EventManager()
|
|
1180
|
+
|
|
1181
|
+
# Configure task worker to publish events
|
|
1182
|
+
async def configure_task_worker_events(worker):
|
|
1183
|
+
# Start the event manager
|
|
1184
|
+
await event_manager.start()
|
|
1185
|
+
|
|
1186
|
+
async def monitor_worker():
|
|
1187
|
+
while True:
|
|
1188
|
+
# Get all tasks in terminal states
|
|
1189
|
+
terminal_tasks = await worker.get_all_tasks(
|
|
1190
|
+
status=["completed", "failed", "cancelled"]
|
|
1191
|
+
)
|
|
1192
|
+
|
|
1193
|
+
for task_info in terminal_tasks:
|
|
1194
|
+
# Check if we've already published an event for this task
|
|
1195
|
+
if not event_manager.is_processed(task_info.id):
|
|
1196
|
+
# Build event data based on task state
|
|
1197
|
+
event_data = {
|
|
1198
|
+
"task_id": task_info.id,
|
|
1199
|
+
"status": task_info.status,
|
|
1200
|
+
"timestamp": asyncio.get_event_loop().time()
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
# Add status-specific data
|
|
1204
|
+
if task_info.status == "completed":
|
|
1205
|
+
event_data["result"] = task_info.result
|
|
1206
|
+
elif task_info.status == "failed":
|
|
1207
|
+
event_data["error"] = task_info.error
|
|
1208
|
+
|
|
1209
|
+
# Get group ID from metadata or use task_id as fallback
|
|
1210
|
+
group_id = task_info.metadata.get("group_id", task_info.id)
|
|
1211
|
+
|
|
1212
|
+
# Publish the event
|
|
1213
|
+
await event_manager.publish_event(
|
|
1214
|
+
event_id=task_info.id,
|
|
1215
|
+
group_id=group_id,
|
|
1216
|
+
event_data=event_data
|
|
1217
|
+
)
|
|
1218
|
+
|
|
1219
|
+
# Short sleep to avoid CPU spinning
|
|
1220
|
+
await asyncio.sleep(0.1)
|
|
1221
|
+
|
|
1222
|
+
# Start the monitoring task
|
|
1223
|
+
monitor_task = asyncio.create_task(monitor_worker())
|
|
1224
|
+
return monitor_task
|
|
1225
|
+
|
|
1226
|
+
# Define a task that reports progress events
|
|
1227
|
+
@task("computation_task")
|
|
1228
|
+
async def computation_task(data, computation_id, delay=0.5):
|
|
1229
|
+
"""Task that reports progress via events."""
|
|
1230
|
+
result = {"status": "processing", "computation_id": computation_id}
|
|
1231
|
+
total_steps = 5
|
|
1232
|
+
|
|
1233
|
+
for step in range(1, total_steps + 1):
|
|
1234
|
+
# Simulate work
|
|
1235
|
+
await asyncio.sleep(delay)
|
|
1236
|
+
|
|
1237
|
+
# Update progress
|
|
1238
|
+
progress = step / total_steps
|
|
1239
|
+
|
|
1240
|
+
# Publish step completion event
|
|
1241
|
+
event_data = {
|
|
1242
|
+
"computation_id": computation_id,
|
|
1243
|
+
"step": step,
|
|
1244
|
+
"total_steps": total_steps,
|
|
1245
|
+
"progress": progress
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
await event_manager.publish_event(
|
|
1249
|
+
event_id=f"{computation_id}_step_{step}",
|
|
1250
|
+
group_id=computation_id,
|
|
1251
|
+
event_data=event_data
|
|
1252
|
+
)
|
|
1253
|
+
|
|
1254
|
+
# Update final status
|
|
1255
|
+
result["status"] = "completed"
|
|
1256
|
+
|
|
1257
|
+
# Publish completion event
|
|
1258
|
+
await event_manager.publish_event(
|
|
1259
|
+
event_id=f"{computation_id}_completed",
|
|
1260
|
+
group_id=computation_id,
|
|
1261
|
+
event_data={
|
|
1262
|
+
"computation_id": computation_id,
|
|
1263
|
+
"status": "completed",
|
|
1264
|
+
"result": result
|
|
1265
|
+
}
|
|
1266
|
+
)
|
|
1267
|
+
|
|
1268
|
+
return result
|
|
1269
|
+
|
|
1270
|
+
# Example of subscribing to events
|
|
1271
|
+
async def subscribe_to_task_events(computation_id):
|
|
1272
|
+
async with EventSubscription(computation_id) as subscription:
|
|
1273
|
+
# Collect events until we see a completion event
|
|
1274
|
+
events = await subscription.collect_events(
|
|
1275
|
+
until_condition=lambda e: e.get("status") == "completed",
|
|
1276
|
+
timeout=30.0
|
|
1277
|
+
)
|
|
1278
|
+
|
|
1279
|
+
# Process collected events
|
|
1280
|
+
return events
|
|
1281
|
+
```
|
|
1282
|
+
|
|
1283
|
+
### Complete Example with Web Integration
|
|
1284
|
+
|
|
1285
|
+
Here's a full example showing how to integrate task events with a web application:
|
|
1286
|
+
|
|
1287
|
+
```python
|
|
1288
|
+
import asyncio
|
|
1289
|
+
import uuid
|
|
1290
|
+
from fastapi import FastAPI, WebSocket
|
|
1291
|
+
from contextlib import asynccontextmanager
|
|
1292
|
+
from async_task_worker import AsyncTaskWorker, task, create_task_worker_router
|
|
1293
|
+
from async_events import event_manager, EventSubscription
|
|
1294
|
+
|
|
1295
|
+
# Create worker
|
|
1296
|
+
worker = AsyncTaskWorker(max_workers=5)
|
|
1297
|
+
|
|
1298
|
+
# Configure the event system integration
|
|
1299
|
+
event_monitor_task = None
|
|
1300
|
+
|
|
1301
|
+
@asynccontextmanager
|
|
1302
|
+
async def lifespan(app: FastAPI):
|
|
1303
|
+
global event_monitor_task
|
|
1304
|
+
# Start worker
|
|
1305
|
+
await worker.start()
|
|
1306
|
+
|
|
1307
|
+
# Start event manager
|
|
1308
|
+
await event_manager.start()
|
|
1309
|
+
|
|
1310
|
+
# Configure event monitoring
|
|
1311
|
+
event_monitor_task = await configure_task_worker_events(worker)
|
|
1312
|
+
|
|
1313
|
+
yield
|
|
1314
|
+
|
|
1315
|
+
# Cleanup
|
|
1316
|
+
if event_monitor_task:
|
|
1317
|
+
event_monitor_task.cancel()
|
|
1318
|
+
try:
|
|
1319
|
+
await event_monitor_task
|
|
1320
|
+
except asyncio.CancelledError:
|
|
1321
|
+
pass
|
|
1322
|
+
|
|
1323
|
+
await event_manager.stop()
|
|
1324
|
+
await worker.stop()
|
|
1325
|
+
|
|
1326
|
+
# Create FastAPI app
|
|
1327
|
+
app = FastAPI(lifespan=lifespan)
|
|
1328
|
+
|
|
1329
|
+
# Include the task worker API
|
|
1330
|
+
app.include_router(create_task_worker_router(worker))
|
|
1331
|
+
|
|
1332
|
+
# WebSocket endpoint for real-time task events
|
|
1333
|
+
@app.websocket("/ws/tasks/{group_id}")
|
|
1334
|
+
async def websocket_endpoint(websocket: WebSocket, group_id: str):
|
|
1335
|
+
await websocket.accept()
|
|
1336
|
+
|
|
1337
|
+
# Subscribe to events for this group
|
|
1338
|
+
subscriber_id, queue = await event_manager.subscribe(group_id)
|
|
1339
|
+
|
|
1340
|
+
try:
|
|
1341
|
+
# Get historical events first
|
|
1342
|
+
filter_obj = GroupFilter(group_id=group_id)
|
|
1343
|
+
historical_events = await event_manager.get_recent_events(filter_obj)
|
|
1344
|
+
|
|
1345
|
+
# Send historical events
|
|
1346
|
+
for event in historical_events:
|
|
1347
|
+
await websocket.send_json(event)
|
|
1348
|
+
|
|
1349
|
+
# Listen for new events
|
|
1350
|
+
while True:
|
|
1351
|
+
# Wait for next event
|
|
1352
|
+
try:
|
|
1353
|
+
event = await asyncio.wait_for(queue.get(), timeout=30)
|
|
1354
|
+
await websocket.send_json(event)
|
|
1355
|
+
except asyncio.TimeoutError:
|
|
1356
|
+
# Send ping to keep connection alive
|
|
1357
|
+
await websocket.send_json({"type": "ping"})
|
|
1358
|
+
except Exception as e:
|
|
1359
|
+
print(f"WebSocket error: {str(e)}")
|
|
1360
|
+
finally:
|
|
1361
|
+
# Unsubscribe when connection closes
|
|
1362
|
+
await event_manager.unsubscribe(subscriber_id)
|
|
1363
|
+
|
|
1364
|
+
# API endpoint to start a computation task
|
|
1365
|
+
@app.post("/computations")
|
|
1366
|
+
async def start_computation(data: dict):
|
|
1367
|
+
computation_id = str(uuid.uuid4())
|
|
1368
|
+
|
|
1369
|
+
# Add task to worker with group_id in metadata
|
|
1370
|
+
task_id = await worker.add_task(
|
|
1371
|
+
computation_task,
|
|
1372
|
+
data=data,
|
|
1373
|
+
computation_id=computation_id,
|
|
1374
|
+
metadata={"group_id": computation_id}
|
|
1375
|
+
)
|
|
1376
|
+
|
|
1377
|
+
return {
|
|
1378
|
+
"computation_id": computation_id,
|
|
1379
|
+
"task_id": task_id,
|
|
1380
|
+
"websocket_url": f"/ws/tasks/{computation_id}"
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
# Frontend JavaScript to connect to the WebSocket
|
|
1384
|
+
"""
|
|
1385
|
+
// Connect to the WebSocket for task events
|
|
1386
|
+
function connectToTaskEvents(computationId) {
|
|
1387
|
+
const socket = new WebSocket(`ws://${window.location.host}/ws/tasks/${computationId}`);
|
|
1388
|
+
|
|
1389
|
+
socket.onmessage = (event) => {
|
|
1390
|
+
const data = JSON.parse(event.data);
|
|
1391
|
+
|
|
1392
|
+
// Ignore ping messages
|
|
1393
|
+
if (data.type === 'ping') return;
|
|
1394
|
+
|
|
1395
|
+
// Update UI based on event type
|
|
1396
|
+
if (data.status === 'completed') {
|
|
1397
|
+
// Show completion
|
|
1398
|
+
showResult(data.result);
|
|
1399
|
+
} else if (data.progress !== undefined) {
|
|
1400
|
+
// Update progress bar
|
|
1401
|
+
updateProgress(data.progress);
|
|
1402
|
+
}
|
|
1403
|
+
};
|
|
1404
|
+
|
|
1405
|
+
return socket;
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
// Start a new computation and connect to its events
|
|
1409
|
+
async function startComputation(data) {
|
|
1410
|
+
const response = await fetch('/computations', {
|
|
1411
|
+
method: 'POST',
|
|
1412
|
+
headers: {
|
|
1413
|
+
'Content-Type': 'application/json'
|
|
1414
|
+
},
|
|
1415
|
+
body: JSON.stringify(data)
|
|
1416
|
+
});
|
|
1417
|
+
|
|
1418
|
+
const result = await response.json();
|
|
1419
|
+
|
|
1420
|
+
// Connect to WebSocket for real-time updates
|
|
1421
|
+
const socket = connectToTaskEvents(result.computation_id);
|
|
1422
|
+
|
|
1423
|
+
return {
|
|
1424
|
+
computationId: result.computation_id,
|
|
1425
|
+
taskId: result.task_id,
|
|
1426
|
+
socket: socket
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
"""
|
|
1430
|
+
```
|
|
1431
|
+
|
|
1432
|
+
### Advanced Event Patterns
|
|
1433
|
+
|
|
1434
|
+
#### Reactive Task Monitoring Dashboard
|
|
1435
|
+
|
|
1436
|
+
```python
|
|
1437
|
+
async def monitor_all_tasks(worker, dashboard_id):
|
|
1438
|
+
"""Create a real-time dashboard of all tasks."""
|
|
1439
|
+
# Subscribe to all task events (using special group)
|
|
1440
|
+
subscriber_id, queue = await event_manager.subscribe("all_tasks")
|
|
1441
|
+
|
|
1442
|
+
# Task to forward all task events to the dashboard
|
|
1443
|
+
async def forward_events():
|
|
1444
|
+
while True:
|
|
1445
|
+
event = await queue.get()
|
|
1446
|
+
# Update dashboard UI with event data
|
|
1447
|
+
await update_dashboard(dashboard_id, event)
|
|
1448
|
+
|
|
1449
|
+
# Monitor task events from worker
|
|
1450
|
+
async def process_task_events():
|
|
1451
|
+
while True:
|
|
1452
|
+
tasks = await worker.get_all_tasks()
|
|
1453
|
+
|
|
1454
|
+
for task in tasks:
|
|
1455
|
+
# Create event data from task info
|
|
1456
|
+
event_data = {
|
|
1457
|
+
"task_id": task.id,
|
|
1458
|
+
"status": task.status,
|
|
1459
|
+
"progress": task.progress,
|
|
1460
|
+
"created_at": task.created_at.isoformat(),
|
|
1461
|
+
"type": task.metadata.get("task_type", "unknown")
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
# Publish to both specific task group and all_tasks group
|
|
1465
|
+
await event_manager.publish_event(
|
|
1466
|
+
event_id=f"{task.id}_{task.status}",
|
|
1467
|
+
group_id="all_tasks", # Dashboard group
|
|
1468
|
+
event_data=event_data
|
|
1469
|
+
)
|
|
1470
|
+
|
|
1471
|
+
await asyncio.sleep(1)
|
|
1472
|
+
|
|
1473
|
+
# Start both tasks
|
|
1474
|
+
event_task = asyncio.create_task(forward_events())
|
|
1475
|
+
monitor_task = asyncio.create_task(process_task_events())
|
|
1476
|
+
|
|
1477
|
+
return event_task, monitor_task
|
|
1478
|
+
```
|
|
1479
|
+
|
|
1480
|
+
#### Chained Task Processing with Events
|
|
1481
|
+
|
|
1482
|
+
```python
|
|
1483
|
+
@task("initial_processor")
|
|
1484
|
+
async def initial_processor(data):
|
|
1485
|
+
result = process_initial_data(data)
|
|
1486
|
+
|
|
1487
|
+
# Publish completion event
|
|
1488
|
+
await event_manager.publish_event(
|
|
1489
|
+
event_id=f"initial_{data['id']}",
|
|
1490
|
+
group_id=data["id"],
|
|
1491
|
+
event_data={
|
|
1492
|
+
"stage": "initial",
|
|
1493
|
+
"id": data["id"],
|
|
1494
|
+
"result": result
|
|
1495
|
+
}
|
|
1496
|
+
)
|
|
1497
|
+
|
|
1498
|
+
return result
|
|
1499
|
+
|
|
1500
|
+
@task("secondary_processor")
|
|
1501
|
+
async def secondary_processor(initial_result):
|
|
1502
|
+
# Process the result from the initial task
|
|
1503
|
+
final_result = process_final_data(initial_result)
|
|
1504
|
+
|
|
1505
|
+
# Publish completion event
|
|
1506
|
+
await event_manager.publish_event(
|
|
1507
|
+
event_id=f"secondary_{initial_result['id']}",
|
|
1508
|
+
group_id=initial_result["id"],
|
|
1509
|
+
event_data={
|
|
1510
|
+
"stage": "secondary",
|
|
1511
|
+
"id": initial_result["id"],
|
|
1512
|
+
"result": final_result
|
|
1513
|
+
}
|
|
1514
|
+
)
|
|
1515
|
+
|
|
1516
|
+
return final_result
|
|
1517
|
+
|
|
1518
|
+
# Event-driven task chain
|
|
1519
|
+
async def process_data_chain(data):
|
|
1520
|
+
data_id = data["id"]
|
|
1521
|
+
|
|
1522
|
+
# Start a subscription for this data chain
|
|
1523
|
+
async with EventSubscription(data_id) as subscription:
|
|
1524
|
+
# Start initial processing
|
|
1525
|
+
initial_task_id = await worker.add_task(
|
|
1526
|
+
initial_processor,
|
|
1527
|
+
data=data,
|
|
1528
|
+
metadata={"group_id": data_id}
|
|
1529
|
+
)
|
|
1530
|
+
|
|
1531
|
+
# Wait for initial processing event
|
|
1532
|
+
initial_event = await subscription.wait_for_completion_event(timeout=30.0)
|
|
1533
|
+
|
|
1534
|
+
if not initial_event:
|
|
1535
|
+
raise TimeoutError("Initial processing timed out")
|
|
1536
|
+
|
|
1537
|
+
# Start secondary processing with the result from the initial task
|
|
1538
|
+
secondary_task_id = await worker.add_task(
|
|
1539
|
+
secondary_processor,
|
|
1540
|
+
initial_result=initial_event["result"],
|
|
1541
|
+
metadata={"group_id": data_id}
|
|
1542
|
+
)
|
|
1543
|
+
|
|
1544
|
+
# Wait for secondary processing event
|
|
1545
|
+
secondary_event = await subscription.wait_for_completion_event(timeout=30.0)
|
|
1546
|
+
|
|
1547
|
+
if not secondary_event:
|
|
1548
|
+
raise TimeoutError("Secondary processing timed out")
|
|
1549
|
+
|
|
1550
|
+
return secondary_event["result"]
|
|
1551
|
+
```
|
|
1552
|
+
|
|
1553
|
+
### Server-Sent Events (SSE) Integration
|
|
1554
|
+
|
|
1555
|
+
For web applications, you can use the built-in SSE client to stream task events to browsers:
|
|
1556
|
+
|
|
1557
|
+
```python
|
|
1558
|
+
from fastapi import FastAPI, Request
|
|
1559
|
+
from fastapi.responses import StreamingResponse
|
|
1560
|
+
from async_events import event_manager
|
|
1561
|
+
|
|
1562
|
+
app = FastAPI()
|
|
1563
|
+
|
|
1564
|
+
@app.get("/events/{task_id}")
|
|
1565
|
+
async def event_stream(request: Request, task_id: str):
|
|
1566
|
+
async def generate_events():
|
|
1567
|
+
# Subscribe to events for this task
|
|
1568
|
+
subscriber_id, queue = await event_manager.subscribe(task_id)
|
|
1569
|
+
|
|
1570
|
+
try:
|
|
1571
|
+
# Send SSE headers
|
|
1572
|
+
yield "event: connected\ndata: {\"task_id\":\"" + task_id + "\"}\n\n"
|
|
1573
|
+
|
|
1574
|
+
# Stream events until client disconnects
|
|
1575
|
+
while True:
|
|
1576
|
+
if await request.is_disconnected():
|
|
1577
|
+
break
|
|
1578
|
+
|
|
1579
|
+
try:
|
|
1580
|
+
# Wait for next event with timeout for keep-alive
|
|
1581
|
+
event = await asyncio.wait_for(queue.get(), timeout=15)
|
|
1582
|
+
|
|
1583
|
+
# Format as SSE
|
|
1584
|
+
event_name = event.get("status", "update")
|
|
1585
|
+
event_data = json.dumps(event)
|
|
1586
|
+
yield f"event: {event_name}\ndata: {event_data}\n\n"
|
|
1587
|
+
except asyncio.TimeoutError:
|
|
1588
|
+
# Send keep-alive comment
|
|
1589
|
+
yield ": ping\n\n"
|
|
1590
|
+
finally:
|
|
1591
|
+
# Unsubscribe when client disconnects
|
|
1592
|
+
await event_manager.unsubscribe(subscriber_id)
|
|
1593
|
+
|
|
1594
|
+
return StreamingResponse(
|
|
1595
|
+
generate_events(),
|
|
1596
|
+
media_type="text/event-stream"
|
|
1597
|
+
)
|
|
1598
|
+
```
|
|
1599
|
+
|
|
1600
|
+
### Configuration Options
|
|
1601
|
+
|
|
1602
|
+
The event system provides several configuration options:
|
|
1603
|
+
|
|
1604
|
+
```python
|
|
1605
|
+
# Create event manager with custom settings
|
|
1606
|
+
custom_event_manager = EventManager(
|
|
1607
|
+
result_ttl=1800, # Keep events in memory for 30 minutes
|
|
1608
|
+
)
|
|
1609
|
+
|
|
1610
|
+
# Start the event manager
|
|
1611
|
+
await custom_event_manager.start()
|
|
1612
|
+
|
|
1613
|
+
# Clean up when done
|
|
1614
|
+
await custom_event_manager.stop()
|
|
1615
|
+
```
|
|
1616
|
+
|
|
1617
|
+
By integrating the async_task_worker with the event system, you can build real-time dashboards, notification systems, and event-driven processing chains that react immediately to task state changes.
|
|
1618
|
+
|
|
1619
|
+
|
|
1157
1620
|
## License
|
|
1158
1621
|
|
|
1159
1622
|
MIT
|