|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Copyright 2025 The Dapr Authors |
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +Unless required by applicable law or agreed to in writing, software |
| 9 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +See the License for the specific language governing permissions and |
| 12 | +limitations under the License. |
| 13 | +""" |
| 14 | + |
| 15 | +from dapr.ext.workflow import ( # noqa: E402 |
| 16 | + AsyncWorkflowContext, |
| 17 | + DaprWorkflowClient, |
| 18 | + WorkflowActivityContext, |
| 19 | + WorkflowRuntime, |
| 20 | + WorkflowStatus, |
| 21 | +) |
| 22 | + |
| 23 | +"""Example demonstrating async activities with HTTP requests. |
| 24 | +
|
| 25 | +This example shows how to use async activities to perform I/O-bound operations |
| 26 | +like HTTP requests without blocking the worker thread pool. |
| 27 | +""" |
| 28 | + |
| 29 | + |
| 30 | +wfr = WorkflowRuntime() |
| 31 | + |
| 32 | + |
| 33 | +@wfr.activity(name='fetch_url') |
| 34 | +async def fetch_url(ctx: WorkflowActivityContext, url: str) -> dict: |
| 35 | + """Async activity that fetches data from a URL. |
| 36 | +
|
| 37 | + This demonstrates using aiohttp for non-blocking HTTP requests. |
| 38 | + In production, you would handle errors, timeouts, and retries. |
| 39 | + """ |
| 40 | + try: |
| 41 | + import aiohttp |
| 42 | + except ImportError: |
| 43 | + # Fallback if aiohttp is not installed |
| 44 | + return { |
| 45 | + 'url': url, |
| 46 | + 'status': 'error', |
| 47 | + 'message': 'aiohttp not installed. Install with: pip install aiohttp', |
| 48 | + } |
| 49 | + |
| 50 | + try: |
| 51 | + async with aiohttp.ClientSession() as session: |
| 52 | + async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as response: |
| 53 | + status = response.status |
| 54 | + if status == 200: |
| 55 | + # For JSON responses |
| 56 | + try: |
| 57 | + data = await response.json() |
| 58 | + return {'url': url, 'status': status, 'data': data} |
| 59 | + except Exception: |
| 60 | + # For text responses |
| 61 | + text = await response.text() |
| 62 | + return { |
| 63 | + 'url': url, |
| 64 | + 'status': status, |
| 65 | + 'length': len(text), |
| 66 | + 'preview': text[:100], |
| 67 | + } |
| 68 | + else: |
| 69 | + return {'url': url, 'status': status, 'error': 'HTTP error'} |
| 70 | + except Exception as e: |
| 71 | + return {'url': url, 'status': 'error', 'message': str(e)} |
| 72 | + |
| 73 | + |
| 74 | +@wfr.activity(name='process_data') |
| 75 | +def process_data(ctx: WorkflowActivityContext, data: dict) -> dict: |
| 76 | + """Sync activity that processes fetched data. |
| 77 | +
|
| 78 | + This shows that sync and async activities can coexist in the same workflow. |
| 79 | + """ |
| 80 | + return { |
| 81 | + 'processed': True, |
| 82 | + 'url_count': len([k for k in data if k.startswith('url_')]), |
| 83 | + 'summary': f'Processed {len(data)} items', |
| 84 | + } |
| 85 | + |
| 86 | + |
| 87 | +@wfr.async_workflow(name='fetch_multiple_urls_async') |
| 88 | +async def fetch_multiple_urls(ctx: AsyncWorkflowContext, urls: list[str]) -> dict: |
| 89 | + """Orchestrator that fetches multiple URLs in parallel using async activities. |
| 90 | +
|
| 91 | + This demonstrates: |
| 92 | + - Calling async activities from async workflows |
| 93 | + - Fan-out/fan-in pattern with async activities |
| 94 | + - Mixing async and sync activities |
| 95 | + """ |
| 96 | + # Fan-out: Schedule all URL fetches in parallel |
| 97 | + fetch_tasks = [ctx.call_activity(fetch_url, input=url) for url in urls] |
| 98 | + |
| 99 | + # Fan-in: Wait for all to complete |
| 100 | + results = await ctx.when_all(fetch_tasks) |
| 101 | + |
| 102 | + # Create a dictionary of results |
| 103 | + data = {f'url_{i}': result for i, result in enumerate(results)} |
| 104 | + |
| 105 | + # Process the aggregated data with a sync activity |
| 106 | + summary = await ctx.call_activity(process_data, input=data) |
| 107 | + |
| 108 | + return {'results': data, 'summary': summary} |
| 109 | + |
| 110 | + |
| 111 | +def main(): |
| 112 | + """Run the example workflow.""" |
| 113 | + # Example URLs to fetch (using httpbin.org for testing) |
| 114 | + test_urls = [ |
| 115 | + 'https://httpbin.org/json', |
| 116 | + 'https://httpbin.org/uuid', |
| 117 | + 'https://httpbin.org/user-agent', |
| 118 | + ] |
| 119 | + |
| 120 | + wfr.start() |
| 121 | + client = DaprWorkflowClient() |
| 122 | + |
| 123 | + try: |
| 124 | + instance_id = 'async_http_activity_example' |
| 125 | + print(f'Starting workflow {instance_id}...') |
| 126 | + |
| 127 | + # Schedule the workflow |
| 128 | + client.schedule_new_workflow( |
| 129 | + workflow=fetch_multiple_urls, instance_id=instance_id, input=test_urls |
| 130 | + ) |
| 131 | + |
| 132 | + # Wait for completion |
| 133 | + wf_state = client.wait_for_workflow_completion(instance_id, timeout_in_seconds=60) |
| 134 | + |
| 135 | + print(f'\nWorkflow status: {wf_state.runtime_status}') |
| 136 | + |
| 137 | + if wf_state.runtime_status == WorkflowStatus.COMPLETED: |
| 138 | + print(f'Workflow output: {wf_state.serialized_output}') |
| 139 | + print('\n✓ Workflow completed successfully!') |
| 140 | + else: |
| 141 | + print('✗ Workflow did not complete successfully') |
| 142 | + return 1 |
| 143 | + |
| 144 | + finally: |
| 145 | + wfr.shutdown() |
| 146 | + |
| 147 | + return 0 |
| 148 | + |
| 149 | + |
| 150 | +if __name__ == '__main__': |
| 151 | + import sys |
| 152 | + |
| 153 | + sys.exit(main()) |
0 commit comments