Skip to content

Commit 189fecb

Browse files
committed
cleanup
Signed-off-by: Filinto Duran <[email protected]>
1 parent 2e97302 commit 189fecb

File tree

5 files changed

+7
-145
lines changed

5 files changed

+7
-145
lines changed

durabletask/aio/ASYNCIO_ENHANCEMENTS.md

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -205,28 +205,17 @@ async def competitive_workflow(ctx, input_data):
205205
```
206206

207207
### Error Handling with Context
208+
208209
```python
209210
async def robust_workflow(ctx, input_data):
210211
try:
211212
return await ctx.call_activity("risky_activity")
212213
except Exception as e:
213214
# Enhanced error will include workflow context
214-
debug_info = ctx.get_debug_info()
215+
debug_info = ctx._get_info_snapshot()
215216
return {"error": str(e), "debug": debug_info}
216217
```
217218

218-
### Cleanup Tasks
219-
```python
220-
async def workflow_with_cleanup(ctx, input_data):
221-
async with ctx: # Automatic cleanup
222-
# Register cleanup tasks
223-
ctx.add_cleanup(lambda: print("Workflow completed"))
224-
225-
result = await ctx.call_activity("main_work")
226-
return result
227-
# Cleanup tasks run automatically here
228-
```
229-
230219
## Best Practices
231220

232221
1. **Use deterministic alternatives**:
@@ -245,12 +234,7 @@ async def workflow_with_cleanup(ctx, input_data):
245234
result = await ctx.with_timeout(ctx.call_activity("external_api"), 30.0)
246235
```
247236

248-
4. **Use cleanup tasks for resource management**:
249-
```python
250-
ctx.add_cleanup(lambda: cleanup_resources())
251-
```
252-
253-
5. **Enable debug mode during development**:
237+
4. **Enable debug mode during development**:
254238
```bash
255239
export DAPR_WF_DEBUG=true
256240
```

durabletask/aio/context.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -337,15 +337,6 @@ async def __aexit__(
337337

338338
self._cleanup_tasks.clear()
339339

340-
def add_cleanup(self, cleanup_fn: Callable[[], Any]) -> None:
341-
"""
342-
Add a cleanup function to be called when the context exits.
343-
344-
Args:
345-
cleanup_fn: Function to call during cleanup
346-
"""
347-
self._cleanup_tasks.append(cleanup_fn)
348-
349340
# Debug and monitoring
350341
def _log_operation(self, operation: str, details: Dict[str, Any]) -> None:
351342
"""Log workflow operation for debugging."""
@@ -361,7 +352,7 @@ def _log_operation(self, operation: str, details: Dict[str, Any]) -> None:
361352
self._operation_history.append(entry)
362353
print(f"[WORKFLOW DEBUG] {operation}: {details}")
363354

364-
def get_debug_info(self) -> Dict[str, Any]:
355+
def _get_info_snapshot(self) -> Dict[str, Any]:
365356
"""
366357
Get debug information about the workflow execution.
367358

tests/aio/test_asyncio_compat_enhanced.py renamed to tests/aio/test_asyncio_enhanced_additions.py

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -94,34 +94,12 @@ def test_get_debug_info(self):
9494
ctx = AsyncWorkflowContext(self.mock_base_ctx)
9595
ctx._log_operation("test_op", {"param": "value"})
9696

97-
debug_info = ctx.get_debug_info()
97+
debug_info = ctx._get_info_snapshot()
9898

9999
assert debug_info["instance_id"] == "test-instance-123"
100100
assert len(debug_info["operation_history"]) == 1
101101
assert debug_info["operation_history"][0]["type"] == "test_op"
102102

103-
def test_cleanup_registry(self):
104-
cleanup_called = []
105-
106-
def cleanup_fn():
107-
cleanup_called.append("sync")
108-
109-
async def async_cleanup_fn():
110-
cleanup_called.append("async")
111-
112-
self.ctx.add_cleanup(cleanup_fn)
113-
self.ctx.add_cleanup(async_cleanup_fn)
114-
115-
# Test cleanup execution
116-
async def test_cleanup():
117-
async with self.ctx:
118-
pass
119-
120-
asyncio.run(test_cleanup())
121-
122-
# Cleanup should be called in reverse order
123-
assert cleanup_called == ["async", "sync"]
124-
125103
def test_activity_logging(self):
126104
with patch.dict(os.environ, {"DAPR_WF_DEBUG": "true"}):
127105
ctx = AsyncWorkflowContext(self.mock_base_ctx)
@@ -274,8 +252,6 @@ def test_strict_mode_secrets_blocking(self):
274252
pass
275253

276254
def test_asyncio_sleep_patching(self):
277-
import asyncio
278-
279255
original_sleep = asyncio.sleep
280256

281257
with _sandbox_scope(self.async_ctx, "best_effort"):

tests/aio/test_context.py

Lines changed: 1 addition & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -316,77 +316,14 @@ def test_operation_logging_in_debug_mode(self):
316316

317317
def test_get_debug_info_method(self):
318318
"""Test get_debug_info() method."""
319-
debug_info = self.ctx.get_debug_info()
319+
debug_info = self.ctx._get_info_snapshot()
320320

321321
assert isinstance(debug_info, dict)
322322
assert debug_info["instance_id"] == "test-instance-123"
323323
assert debug_info["is_replaying"] == False
324324
assert "operation_history" in debug_info
325325
assert "cleanup_tasks_count" in debug_info
326326

327-
def test_add_cleanup_method(self):
328-
"""Test add_cleanup() method."""
329-
cleanup_task = Mock()
330-
331-
self.ctx.add_cleanup(cleanup_task)
332-
333-
assert cleanup_task in self.ctx._cleanup_tasks
334-
335-
def test_async_context_manager(self):
336-
"""Test async context manager functionality."""
337-
cleanup_task1 = Mock()
338-
cleanup_task2 = Mock()
339-
340-
async def test_context_manager():
341-
async with self.ctx:
342-
self.ctx.add_cleanup(cleanup_task1)
343-
self.ctx.add_cleanup(cleanup_task2)
344-
345-
# Run the async context manager
346-
import asyncio
347-
348-
asyncio.run(test_context_manager())
349-
350-
# Cleanup tasks should have been called in reverse order
351-
cleanup_task2.assert_called_once()
352-
cleanup_task1.assert_called_once()
353-
354-
def test_async_context_manager_with_async_cleanup(self):
355-
"""Test async context manager with async cleanup tasks."""
356-
import asyncio
357-
358-
async_cleanup = Mock()
359-
360-
async def _noop():
361-
return None
362-
363-
async_cleanup.return_value = _noop()
364-
365-
async def test_async_cleanup():
366-
async with self.ctx:
367-
self.ctx.add_cleanup(async_cleanup)
368-
369-
# Should handle async cleanup tasks
370-
asyncio.run(test_async_cleanup())
371-
372-
def test_async_context_manager_cleanup_error_handling(self):
373-
"""Test that cleanup errors don't prevent other cleanups."""
374-
failing_cleanup = Mock(side_effect=Exception("Cleanup failed"))
375-
working_cleanup = Mock()
376-
377-
async def test_cleanup_errors():
378-
async with self.ctx:
379-
self.ctx.add_cleanup(failing_cleanup)
380-
self.ctx.add_cleanup(working_cleanup)
381-
382-
# Should not raise error and should call both cleanups
383-
import asyncio
384-
385-
asyncio.run(test_cleanup_errors())
386-
387-
failing_cleanup.assert_called_once()
388-
working_cleanup.assert_called_once()
389-
390327
def test_detection_disabled_property(self):
391328
"""Test _detection_disabled property."""
392329
import os

tests/aio/test_context_simple.py

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
These tests focus on the actual implementation rather than expected features.
1616
"""
1717

18-
import asyncio
1918
import random
2019
import uuid
2120
from datetime import datetime, timedelta
@@ -261,34 +260,9 @@ def test_continue_as_new_method(self):
261260
# Should not raise error even if base context doesn't support it
262261
self.ctx.continue_as_new(new_input)
263262

264-
def test_add_cleanup_method(self):
265-
"""Test add_cleanup() method."""
266-
cleanup_task = Mock()
267-
268-
self.ctx.add_cleanup(cleanup_task)
269-
270-
assert cleanup_task in self.ctx._cleanup_tasks
271-
272-
def test_async_context_manager(self):
273-
"""Test async context manager functionality."""
274-
cleanup_task1 = Mock()
275-
cleanup_task2 = Mock()
276-
277-
async def test_context_manager():
278-
async with self.ctx:
279-
self.ctx.add_cleanup(cleanup_task1)
280-
self.ctx.add_cleanup(cleanup_task2)
281-
282-
# Run the async context manager
283-
asyncio.run(test_context_manager())
284-
285-
# Cleanup tasks should have been called in reverse order
286-
cleanup_task2.assert_called_once()
287-
cleanup_task1.assert_called_once()
288-
289263
def test_get_debug_info_method(self):
290264
"""Test get_debug_info() method."""
291-
debug_info = self.ctx.get_debug_info()
265+
debug_info = self.ctx._get_info_snapshot()
292266

293267
assert isinstance(debug_info, dict)
294268
assert debug_info["instance_id"] == "test-instance-123"

0 commit comments

Comments
 (0)