async-task-worker 0.2.0__tar.gz → 0.3.1__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.
Files changed (28) hide show
  1. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/CLAUDE.md +1 -0
  2. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/PKG-INFO +324 -50
  3. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/README.md +323 -49
  4. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/pyproject.toml +3 -2
  5. async_task_worker-0.3.1/src/async_cache/__init__.py +83 -0
  6. async_task_worker-0.3.1/src/async_cache/adapters/__init__.py +11 -0
  7. async_task_worker-0.3.1/src/async_cache/adapters/memory.py +122 -0
  8. async_task_worker-0.3.1/src/async_cache/adapters/redis.py +182 -0
  9. async_task_worker-0.3.1/src/async_cache/core.py +680 -0
  10. async_task_worker-0.3.1/src/async_cache/exceptions.py +16 -0
  11. async_task_worker-0.3.1/src/async_cache/key_utils.py +136 -0
  12. async_task_worker-0.3.1/src/async_cache/serialization.py +230 -0
  13. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/src/async_task_worker/__init__.py +15 -21
  14. async_task_worker-0.3.1/src/async_task_worker/adapters/__init__.py +3 -0
  15. async_task_worker-0.3.1/src/async_task_worker/adapters/cache_adapter.py +267 -0
  16. async_task_worker-0.2.0/src/async_task_worker/task_worker_api.py → async_task_worker-0.3.1/src/async_task_worker/api.py +2 -2
  17. async_task_worker-0.2.0/src/async_task_worker/async_task_worker.py → async_task_worker-0.3.1/src/async_task_worker/core.py +161 -77
  18. async_task_worker-0.2.0/src/async_task_worker/task_executor.py → async_task_worker-0.3.1/src/async_task_worker/executor.py +69 -11
  19. async_task_worker-0.2.0/src/async_task_worker/task_futures.py → async_task_worker-0.3.1/src/async_task_worker/futures.py +2 -2
  20. async_task_worker-0.2.0/src/async_task_worker/worker_pool.py → async_task_worker-0.3.1/src/async_task_worker/pool.py +29 -10
  21. async_task_worker-0.2.0/src/async_task_worker/task_queue.py → async_task_worker-0.3.1/src/async_task_worker/queue.py +1 -1
  22. async_task_worker-0.2.0/src/async_task_worker/task_status.py → async_task_worker-0.3.1/src/async_task_worker/status.py +22 -21
  23. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/uv.lock +24 -1
  24. async_task_worker-0.2.0/src/async_task_worker/task_cache.py +0 -535
  25. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/.gitignore +0 -0
  26. {async_task_worker-0.2.0 → async_task_worker-0.3.1}/LICENSE +0 -0
  27. /async_task_worker-0.2.0/src/async_task_worker/error_handler.py → /async_task_worker-0.3.1/src/async_task_worker/exceptions.py +0 -0
  28. /async_task_worker-0.2.0/src/async_task_worker/task_registry.py → /async_task_worker-0.3.1/src/async_task_worker/registry.py +0 -0
@@ -9,6 +9,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
9
9
  - Run single test: `pytest tests/test_file.py::test_function_name`
10
10
  - Skip integration tests: `pytest -m "not integration"` (default)
11
11
  - Run only asyncio tests: `pytest -m asyncio`
12
+ - Never perform git add. I manage git manually.
12
13
 
13
14
  ## Code Style Guidelines
14
15
  - Python 3.11+ with strict type annotations
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: async-task-worker
3
- Version: 0.2.0
3
+ Version: 0.3.1
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
@@ -43,6 +43,7 @@ pip install async-task-worker
43
43
  - **Task Registry**: Register task handlers by type
44
44
  - **Worker Pool Architecture**: Decoupled worker pool implementation for improved flexibility
45
45
  - **API Integration**: Ready-to-use FastAPI router for task management
46
+ - **Modular Structure**: Clean, consistent module organization with a logical structure
46
47
 
47
48
  ## Sequence Diagrams
48
49
 
@@ -64,7 +65,7 @@ The system follows a modular, decoupled design:
64
65
  3. **TaskQueue**: Manages prioritized task queuing and retrieval
65
66
  4. **TaskExecutor**: Executes individual tasks with timeout and caching
66
67
  5. **TaskRegistry**: Provides a global registry for task handlers
67
- 6. **TaskCache**: Implements optional result caching
68
+ 6. **AsyncCacheAdapter**: Provides integration with the async_cache package for efficient result caching
68
69
 
69
70
  The workflow proceeds as follows:
70
71
 
@@ -519,10 +520,12 @@ The task worker includes an optional caching system that stores task results to
519
520
 
520
521
  #### How Caching Works
521
522
 
522
- 1. **Cache Key Generation**: A unique key is created for each task based on:
523
+ 1. **Flexible Cache Key Generation**: A unique key is created for each task based on:
523
524
  - Task function name
524
525
  - Positional arguments
525
526
  - Keyword arguments
527
+ - Optional task metadata
528
+ - User-defined custom key functions
526
529
 
527
530
  2. **Lookup Process**:
528
531
  - Before executing a task, the worker checks if the result is already in cache
@@ -542,13 +545,20 @@ The task worker includes an optional caching system that stores task results to
542
545
  worker = AsyncTaskWorker(
543
546
  cache_enabled=True, # Enable the cache
544
547
  cache_ttl=3600, # Default time-to-live: 1 hour (in seconds)
545
- cache_max_size=1000 # Maximum number of entries
548
+ cache_max_size=1000, # Maximum number of entries
549
+ cache_cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
546
550
  )
547
551
 
548
552
  # Disable cache globally but allow per-task override
549
553
  worker = AsyncTaskWorker(
550
554
  cache_enabled=False # Globally disabled
551
555
  )
556
+
557
+ # Disable automatic cleanup of stale mappings
558
+ worker = AsyncTaskWorker(
559
+ cache_enabled=True,
560
+ cleanup_interval=0 # Disable automatic cleanup
561
+ )
552
562
  ```
553
563
 
554
564
  #### Per-Task Cache Options
@@ -560,7 +570,8 @@ task_id = await worker.add_task(
560
570
  arg1,
561
571
  arg2,
562
572
  use_cache=True, # Enable caching for this task
563
- cache_ttl=120 # Custom TTL: 2 minutes
573
+ cache_ttl=120, # Custom TTL: 2 minutes
574
+ metadata={"version": "1.2"} # Optional metadata for key generation
564
575
  )
565
576
 
566
577
  # Bypass cache for a specific task even if globally enabled
@@ -570,6 +581,175 @@ task_id = await worker.add_task(
570
581
  arg2,
571
582
  use_cache=False # Disable caching for this task
572
583
  )
584
+
585
+ # Use a custom cache key function
586
+ task_id = await worker.add_task(
587
+ my_task,
588
+ arg1,
589
+ arg2,
590
+ use_cache=True,
591
+ cache_key_fn=my_custom_key_function # Custom cache key generator
592
+ )
593
+ ```
594
+
595
+ ### Using the Cache Adapter
596
+
597
+ AsyncTaskWorker uses `AsyncCacheAdapter` which provides a clean integration with the `async_cache` package, enabling efficient caching with flexible key generation and storage strategies:
598
+
599
+ ```python
600
+ from async_task_worker import AsyncCacheAdapter
601
+ from async_cache.adapters import RedisCacheAdapter
602
+
603
+ # Using Redis as a cache backend
604
+ import redis.asyncio as redis
605
+
606
+ redis_client = redis.Redis(host='localhost', port=6379, db=0)
607
+ redis_adapter = RedisCacheAdapter(redis_client)
608
+
609
+ cache_adapter = AsyncCacheAdapter(
610
+ default_ttl=3600, # Default TTL: 1 hour
611
+ enabled=True, # Enable caching
612
+ max_serialized_size=5_242_880, # 5MB max serialized size
613
+ validate_keys=True, # Validate cache keys
614
+ cleanup_interval=900, # Cleanup every 15 minutes
615
+ adapter=redis_adapter # Use Redis adapter
616
+ )
617
+
618
+ # Then pass to AsyncTaskWorker
619
+ worker = AsyncTaskWorker(
620
+ max_workers=5,
621
+ cache_adapter=cache_adapter,
622
+ cache_enabled=True
623
+ )
624
+ ```
625
+
626
+ ### Customizable Cache Key Generation
627
+
628
+ The caching system supports flexible, composable cache key functions for advanced caching scenarios.
629
+
630
+ #### Context Dictionary
631
+
632
+ Each cache key function receives a context dictionary containing:
633
+
634
+ ```python
635
+ context = {
636
+ "func_name": "task_function_name",
637
+ "args": (arg1, arg2, ...), # Positional arguments
638
+ "kwargs": {"key1": value1, ...}, # Keyword arguments
639
+ "entry_id": "unique-id", # Optional task/entry ID
640
+ "metadata": {"version": "1.0", ...} # Optional metadata
641
+ }
642
+ ```
643
+
644
+ #### Basic Custom Key Function
645
+
646
+ You can create a custom key function to control exactly how cache keys are generated:
647
+
648
+ ```python
649
+ def version_based_key(context):
650
+ """Generate a cache key based on function name and version."""
651
+ func = context["func_name"]
652
+ version = context.get("metadata", {}).get("version", "1.0")
653
+ return f"{func}:v{version}"
654
+
655
+ # Use the custom key function
656
+ task_id = await worker.add_task(
657
+ process_data,
658
+ dataset,
659
+ use_cache=True,
660
+ metadata={"version": "2.0"},
661
+ cache_key_fn=version_based_key
662
+ )
663
+ ```
664
+
665
+ #### Composable Cache Keys
666
+
667
+ For complex caching scenarios, you can compose multiple key functions together:
668
+
669
+ ```python
670
+ from async_cache import compose_key_functions, extract_key_component
671
+
672
+ # Create component extractors
673
+ user_id = extract_key_component("kwargs.user_id")
674
+ api_version = extract_key_component("metadata.version")
675
+ func_name = extract_key_component("func_name")
676
+
677
+ # Compose them into a single key function
678
+ composite_key = compose_key_functions(func_name, user_id, api_version)
679
+
680
+ # Use the composite key function
681
+ task_id = await worker.add_task(
682
+ get_user_data,
683
+ user_id=123,
684
+ use_cache=True,
685
+ metadata={"version": "v2"},
686
+ cache_key_fn=composite_key
687
+ )
688
+ # Will generate a key like: "get_user_data:123:v2"
689
+ ```
690
+
691
+ #### Key Component Decorator
692
+
693
+ For better readability and reuse, you can use the decorator-based approach:
694
+
695
+ ```python
696
+ from async_cache import key_component, compose_key_functions
697
+
698
+ # Create named components with decorators
699
+ @key_component("user")
700
+ def user_component(context):
701
+ return str(context["kwargs"].get("user_id", "anonymous"))
702
+
703
+ @key_component("region")
704
+ def region_component(context):
705
+ return context["kwargs"].get("region", "global")
706
+
707
+ @key_component() # Uses function name as component name
708
+ def timestamp(context):
709
+ return context.get("metadata", {}).get("timestamp", "0")
710
+
711
+ # Compose named components
712
+ composite_key = compose_key_functions(user_component, region_component, timestamp)
713
+
714
+ # Use in a task
715
+ task_id = await worker.add_task(
716
+ get_regional_data,
717
+ user_id=123,
718
+ region="eu-west",
719
+ use_cache=True,
720
+ metadata={"timestamp": "2023-04-01"},
721
+ cache_key_fn=composite_key
722
+ )
723
+ # Will generate a key like: "user:123:region:eu-west:timestamp:2023-04-01"
724
+ ```
725
+
726
+ #### Cache Utilities
727
+
728
+ ```python
729
+ # Temporarily disable the cache (context manager)
730
+ async with worker.cache._cache.temporarily_disabled():
731
+ # Cache operations in this block will be skipped
732
+ result = await worker.add_task(my_task, arg1, arg2, use_cache=True)
733
+ # The cache is actually bypassed despite use_cache=True
734
+
735
+ # Generate a composite entry ID for consistent cache access
736
+ func_name = "my_func"
737
+ task_id = "b4fd93c8-57e3-4fea-bcc6-04be7499b28f"
738
+ entry_id = task_worker.cache.generate_entry_id(func_name, task_id)
739
+
740
+ # Get cached result using the composite entry ID
741
+ hit, result = await task_worker.cache.get_by_task_id(entry_id)
742
+ if hit:
743
+ print(f"Retrieved cached result: {result}")
744
+
745
+ # Invalidate cache by the same entry ID
746
+ success = await task_worker.cache.invalidate_by_task_id(entry_id)
747
+ if success:
748
+ print("Cache entry successfully invalidated")
749
+
750
+ # Control the background cleanup task
751
+ await task_worker.cache.start_cleanup_task() # Start periodic cleanup
752
+ await task_worker.cache.stop_cleanup_task() # Stop periodic cleanup
573
753
  ```
574
754
 
575
755
  ### Cache Management
@@ -590,69 +770,126 @@ invalidated = await worker.invalidate_cache(task_func, arg1, arg2)
590
770
  await worker.clear_cache()
591
771
  ```
592
772
 
593
- ### Custom Cache Adapters
773
+ ### Cache Adapters
594
774
 
595
- By default, the task worker uses an in-memory cache, but you can create custom cache adapters for persistent storage or distributed caching.
775
+ The `async_cache` package provides several cache adapters that can be used with AsyncTaskWorker:
776
+
777
+ 1. **MemoryCacheAdapter**: In-memory LRU cache (default)
778
+ 2. **RedisCacheAdapter**: Redis-backed distributed cache
596
779
 
597
780
  ```python
598
- from async_task_worker import CacheAdapter
599
- from typing import Any, Optional, Tuple
781
+ # Using Memory Adapter (default)
782
+ from async_cache.adapters import MemoryCacheAdapter
783
+ from async_task_worker import AsyncCacheAdapter
600
784
 
785
+ memory_adapter = MemoryCacheAdapter(max_size=10000)
786
+ cache_adapter = AsyncCacheAdapter(adapter=memory_adapter)
601
787
 
602
- class RedisCache(CacheAdapter):
603
- """Example Redis-based cache adapter"""
788
+ # Using Redis Adapter
789
+ from async_cache.adapters import RedisCacheAdapter
790
+ import redis.asyncio as redis
604
791
 
605
- def __init__(self, redis_client):
606
- self.redis = redis_client
792
+ redis_client = redis.Redis(host='localhost', port=6379, db=0)
793
+ redis_adapter = RedisCacheAdapter(redis_client,
794
+ key_prefix="tasks:",
795
+ serializer="msgpack")
607
796
 
608
- async def get(self, key: str) -> Tuple[bool, Any]:
609
- """Get a value from the cache"""
610
- value = await self.redis.get(key)
611
- if value is None:
612
- return False, None
613
- # Deserialize value (e.g., from JSON or pickle)
614
- deserialized = self._deserialize(value)
615
- return True, deserialized
797
+ cache_adapter = AsyncCacheAdapter(adapter=redis_adapter)
616
798
 
617
- async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
618
- """Set a value in the cache"""
619
- # Serialize value (e.g., to JSON or pickle)
620
- serialized = self._serialize(value)
621
- await self.redis.set(key, serialized, ex=ttl)
799
+ # Pass to AsyncTaskWorker
800
+ worker = AsyncTaskWorker(
801
+ cache_enabled=True,
802
+ cache_adapter=cache_adapter
803
+ )
804
+ ```
622
805
 
623
- async def delete(self, key: str) -> bool:
624
- """Delete a value from the cache"""
625
- result = await self.redis.delete(key)
626
- return result > 0
806
+ ### Real-World Examples
627
807
 
628
- async def clear(self) -> None:
629
- """Clear all items (matching a pattern)"""
630
- # Implementation depends on your Redis usage pattern
631
- # For example, using a prefix for all keys
632
- keys = await self.redis.keys("task_cache:*")
633
- if keys:
634
- await self.redis.delete(*keys)
808
+ #### Version-based Cache Invalidation
635
809
 
636
- def _serialize(self, value):
637
- # Implementation
638
- pass
810
+ ```python
811
+ # Create a cache key function that includes API version
812
+ def versioned_cache_key(context):
813
+ func = context["func_name"]
814
+ version = context.get("metadata", {}).get("api_version", "v1")
815
+ return f"{func}:{version}"
816
+
817
+ # User requests data with v1 API
818
+ task_id1 = await worker.add_task(
819
+ get_user_data,
820
+ user_id=123,
821
+ use_cache=True,
822
+ metadata={"api_version": "v1"},
823
+ cache_key_fn=versioned_cache_key
824
+ )
639
825
 
640
- def _deserialize(self, data):
641
- # Implementation
642
- pass
826
+ # Later, after API update, same data with v2 API
827
+ # Will use a different cache key, not reusing v1 cached result
828
+ task_id2 = await worker.add_task(
829
+ get_user_data,
830
+ user_id=123,
831
+ use_cache=True,
832
+ metadata={"api_version": "v2"},
833
+ cache_key_fn=versioned_cache_key
834
+ )
835
+ ```
643
836
 
837
+ #### Multi-tenant Cache Isolation
644
838
 
645
- # Use custom adapter
646
- import redis.asyncio as redis
839
+ ```python
840
+ # Create a key function that isolates cache by tenant
841
+ tenant_key = compose_key_functions(
842
+ extract_key_component("func_name"),
843
+ extract_key_component("metadata.tenant_id"),
844
+ extract_key_component("args.0") # First arg value
845
+ )
647
846
 
648
- redis_client = redis.Redis(host='localhost', port=6379, db=0)
847
+ # Different tenants share same function but get isolated cache
848
+ for tenant_id in ["tenant1", "tenant2", "tenant3"]:
849
+ task_id = await worker.add_task(
850
+ process_data,
851
+ "sample_data",
852
+ use_cache=True,
853
+ metadata={"tenant_id": tenant_id},
854
+ cache_key_fn=tenant_key
855
+ )
856
+ ```
857
+
858
+ ### Automatic Cleanup of Stale Mappings
859
+
860
+ The cache system includes an automatic cleanup mechanism to prevent memory leaks from orphaned task ID mappings when cache entries expire through TTL:
649
861
 
862
+ ```python
863
+ # Configure a worker with cleanup enabled
650
864
  worker = AsyncTaskWorker(
651
- cache_enabled=True,
652
- cache_adapter=RedisCache(redis_client)
865
+ cache_enabled=True,
866
+ cache_ttl=3600, # 1 hour cache TTL
867
+ cleanup_interval=900 # Clean up stale mappings every 15 minutes
868
+ )
869
+
870
+ # The sequence of events:
871
+ # 1. Add a task with caching enabled
872
+ task_id = await worker.add_task(
873
+ process_data,
874
+ dataset,
875
+ use_cache=True,
876
+ cache_ttl=60 # 1 minute TTL
653
877
  )
878
+
879
+ # 2. The task_id is mapped to its cache key in task_key_map
880
+
881
+ # 3. After 1 minute, the cache entry expires due to TTL
882
+
883
+ # 4. Without cleanup, the mapping would remain in memory indefinitely
884
+
885
+ # 5. With cleanup enabled, the background task periodically checks
886
+ # all mappings and removes any where the cache entry is gone
887
+
888
+ # 6. Result: No memory leaks from expired cache entries
654
889
  ```
655
890
 
891
+ The cleanup task starts automatically with the worker and runs at the configured interval. It only removes mappings when the actual cache entries have expired or been removed, ensuring that all valid mappings are preserved.
892
+
656
893
  ## Advanced Usage
657
894
 
658
895
  ### Task Registry
@@ -747,16 +984,34 @@ print(f"Task failed: {info.error}") # "Value cannot be negative"
747
984
 
748
985
  ### AsyncTaskWorker
749
986
 
750
- - `__init__(max_workers=10, task_timeout=None)`: Initialize worker pool
987
+ - `__init__(max_workers=10, task_timeout=None, cache_adapter=None, cache_enabled=False, cache_ttl=3600)`: Initialize worker pool
751
988
  - `start()`: Start the worker pool
752
989
  - `stop(timeout=5.0)`: Stop the worker pool
753
- - `add_task(task_func, *args, priority=0, task_id=None, metadata=None, **kwargs)`: Add a task to the queue
990
+ - `add_task(task_func, *args, priority=0, task_id=None, metadata=None, use_cache=None, cache_ttl=None, cache_key_fn=None, **kwargs)`: Add a task to the queue
754
991
  - `get_task_info(task_id)`: Get information about a task
755
992
  - `get_all_tasks(status=None, limit=None, older_than=None)`: Get filtered list of tasks
756
993
  - `cancel_task(task_id)`: Cancel a running or pending task
757
994
  - `get_task_future(task_id)`: Get a future that resolves when the task completes
758
995
  - `wait_for_tasks(task_ids, timeout=None)`: Wait for multiple tasks to complete
759
996
  - `wait_for_any_task(task_ids, timeout=None)`: Wait for any of the specified tasks to complete
997
+ - `invalidate_cache(task_func, *args, cache_key_fn=None, **kwargs)`: Invalidate a specific cache entry
998
+ - `clear_cache()`: Clear all cache entries
999
+
1000
+ ### AsyncCacheAdapter
1001
+
1002
+ - `__init__(default_ttl=None, enabled=True, max_serialized_size=10485760, validate_keys=False, cleanup_interval=900, max_size=1000)`: Initialize the cache adapter
1003
+ - `get(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Get cached result
1004
+ - `set(func_name, args, kwargs, result, ttl=None, cache_key_fn=None, task_id=None, metadata=None)`: Store result in cache
1005
+ - `invalidate(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Invalidate specific cache entry
1006
+ - `generate_entry_id(func_name, task_id)`: Generate a composite entry ID for cache operations
1007
+ - `get_by_task_id(task_id)`: Get cached result using only the task ID
1008
+ - `invalidate_by_task_id(task_id)`: Invalidate cache entry by task ID
1009
+ - `clear()`: Clear the entire cache
1010
+ - `start_cleanup_task()`: Start the periodic cleanup task
1011
+ - `stop_cleanup_task()`: Stop the periodic cleanup task
1012
+ - `enabled`: Property to get/set if cache is enabled
1013
+ - `default_ttl`: Property to get/set default TTL
1014
+ - `cleanup_interval`: Property to get/set cleanup interval
760
1015
 
761
1016
  ### WorkerPool
762
1017
 
@@ -880,6 +1135,25 @@ async def check_task(task_id):
880
1135
  return f"Task is {status} ({task_data['progress']*100:.1f}% complete)"
881
1136
  ```
882
1137
 
1138
+ ### Example: Reading Result from Cache by Task ID
1139
+
1140
+ ```python
1141
+ async def get_cached_result(task_worker, func_name, task_id):
1142
+ # Generate the composite entry ID for cache lookup
1143
+ entry_id = task_worker.cache.generate_entry_id(func_name, task_id)
1144
+
1145
+ # Try to get result directly from cache using the entry_id
1146
+ hit, result = await task_worker.cache.get_by_task_id(entry_id)
1147
+
1148
+ if hit:
1149
+ print(f"Retrieved from cache: {result}")
1150
+ return result
1151
+ else:
1152
+ print(f"No cached result found for function {func_name}, task {task_id}")
1153
+ # Fall back to retrieving via task info
1154
+ return await handle_task_not_in_cache(task_worker, task_id)
1155
+ ```
1156
+
883
1157
  ## License
884
1158
 
885
1159
  MIT