async-task-worker 0.2.0__tar.gz → 0.3.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.
Files changed (28) hide show
  1. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/PKG-INFO +294 -50
  2. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/README.md +293 -49
  3. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/pyproject.toml +3 -2
  4. async_task_worker-0.3.0/src/async_cache/__init__.py +83 -0
  5. async_task_worker-0.3.0/src/async_cache/adapters/__init__.py +11 -0
  6. async_task_worker-0.3.0/src/async_cache/adapters/memory.py +122 -0
  7. async_task_worker-0.3.0/src/async_cache/adapters/redis.py +182 -0
  8. async_task_worker-0.3.0/src/async_cache/core.py +680 -0
  9. async_task_worker-0.3.0/src/async_cache/exceptions.py +16 -0
  10. async_task_worker-0.3.0/src/async_cache/key_utils.py +136 -0
  11. async_task_worker-0.3.0/src/async_cache/serialization.py +230 -0
  12. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/src/async_task_worker/__init__.py +15 -21
  13. async_task_worker-0.3.0/src/async_task_worker/adapters/__init__.py +3 -0
  14. async_task_worker-0.3.0/src/async_task_worker/adapters/cache_adapter.py +206 -0
  15. async_task_worker-0.2.0/src/async_task_worker/task_worker_api.py → async_task_worker-0.3.0/src/async_task_worker/api.py +2 -2
  16. async_task_worker-0.2.0/src/async_task_worker/async_task_worker.py → async_task_worker-0.3.0/src/async_task_worker/core.py +113 -79
  17. async_task_worker-0.2.0/src/async_task_worker/task_executor.py → async_task_worker-0.3.0/src/async_task_worker/executor.py +26 -5
  18. async_task_worker-0.2.0/src/async_task_worker/task_futures.py → async_task_worker-0.3.0/src/async_task_worker/futures.py +2 -2
  19. async_task_worker-0.2.0/src/async_task_worker/worker_pool.py → async_task_worker-0.3.0/src/async_task_worker/pool.py +22 -6
  20. async_task_worker-0.2.0/src/async_task_worker/task_queue.py → async_task_worker-0.3.0/src/async_task_worker/queue.py +1 -1
  21. async_task_worker-0.2.0/src/async_task_worker/task_status.py → async_task_worker-0.3.0/src/async_task_worker/status.py +22 -21
  22. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/uv.lock +24 -1
  23. async_task_worker-0.2.0/src/async_task_worker/task_cache.py +0 -535
  24. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/.gitignore +0 -0
  25. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/CLAUDE.md +0 -0
  26. {async_task_worker-0.2.0 → async_task_worker-0.3.0}/LICENSE +0 -0
  27. /async_task_worker-0.2.0/src/async_task_worker/error_handler.py → /async_task_worker-0.3.0/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.0/src/async_task_worker/registry.py +0 -0
@@ -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.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
@@ -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,21 @@ 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
+ validate_keys=True, # Enable validation of cache keys (optional)
550
+ cleanup_interval=900 # Cleanup interval for stale mappings (15 min)
546
551
  )
547
552
 
548
553
  # Disable cache globally but allow per-task override
549
554
  worker = AsyncTaskWorker(
550
555
  cache_enabled=False # Globally disabled
551
556
  )
557
+
558
+ # Disable automatic cleanup of stale mappings
559
+ worker = AsyncTaskWorker(
560
+ cache_enabled=True,
561
+ cleanup_interval=0 # Disable automatic cleanup
562
+ )
552
563
  ```
553
564
 
554
565
  #### Per-Task Cache Options
@@ -560,7 +571,8 @@ task_id = await worker.add_task(
560
571
  arg1,
561
572
  arg2,
562
573
  use_cache=True, # Enable caching for this task
563
- cache_ttl=120 # Custom TTL: 2 minutes
574
+ cache_ttl=120, # Custom TTL: 2 minutes
575
+ metadata={"version": "1.2"} # Optional metadata for key generation
564
576
  )
565
577
 
566
578
  # Bypass cache for a specific task even if globally enabled
@@ -570,6 +582,166 @@ task_id = await worker.add_task(
570
582
  arg2,
571
583
  use_cache=False # Disable caching for this task
572
584
  )
585
+
586
+ # Use a custom cache key function
587
+ task_id = await worker.add_task(
588
+ my_task,
589
+ arg1,
590
+ arg2,
591
+ use_cache=True,
592
+ cache_key_fn=my_custom_key_function # Custom cache key generator
593
+ )
594
+ ```
595
+
596
+ ### Using the Cache Adapter
597
+
598
+ AsyncTaskWorker uses `AsyncCacheAdapter` which provides a clean integration with the `async_cache` package, enabling efficient caching with flexible key generation and storage strategies:
599
+
600
+ ```python
601
+ from async_task_worker import AsyncCacheAdapter
602
+ from async_cache.adapters import RedisCacheAdapter
603
+
604
+ # Using Redis as a cache backend
605
+ import redis.asyncio as redis
606
+
607
+ redis_client = redis.Redis(host='localhost', port=6379, db=0)
608
+ redis_adapter = RedisCacheAdapter(redis_client)
609
+
610
+ cache_adapter = AsyncCacheAdapter(
611
+ default_ttl=3600, # Default TTL: 1 hour
612
+ enabled=True, # Enable caching
613
+ max_serialized_size=5_242_880, # 5MB max serialized size
614
+ validate_keys=True, # Validate cache keys
615
+ cleanup_interval=900, # Cleanup every 15 minutes
616
+ redis_adapter=redis_adapter # Use Redis adapter
617
+ )
618
+
619
+ # Then pass to AsyncTaskWorker
620
+ worker = AsyncTaskWorker(
621
+ max_workers=5,
622
+ cache_adapter=cache_adapter,
623
+ cache_enabled=True
624
+ )
625
+ ```
626
+
627
+ ### Customizable Cache Key Generation
628
+
629
+ The caching system supports flexible, composable cache key functions for advanced caching scenarios.
630
+
631
+ #### Context Dictionary
632
+
633
+ Each cache key function receives a context dictionary containing:
634
+
635
+ ```python
636
+ context = {
637
+ "func_name": "task_function_name",
638
+ "args": (arg1, arg2, ...), # Positional arguments
639
+ "kwargs": {"key1": value1, ...}, # Keyword arguments
640
+ "entry_id": "unique-id", # Optional task/entry ID
641
+ "metadata": {"version": "1.0", ...} # Optional metadata
642
+ }
643
+ ```
644
+
645
+ #### Basic Custom Key Function
646
+
647
+ You can create a custom key function to control exactly how cache keys are generated:
648
+
649
+ ```python
650
+ def version_based_key(context):
651
+ """Generate a cache key based on function name and version."""
652
+ func = context["func_name"]
653
+ version = context.get("metadata", {}).get("version", "1.0")
654
+ return f"{func}:v{version}"
655
+
656
+ # Use the custom key function
657
+ task_id = await worker.add_task(
658
+ process_data,
659
+ dataset,
660
+ use_cache=True,
661
+ metadata={"version": "2.0"},
662
+ cache_key_fn=version_based_key
663
+ )
664
+ ```
665
+
666
+ #### Composable Cache Keys
667
+
668
+ For complex caching scenarios, you can compose multiple key functions together:
669
+
670
+ ```python
671
+ from async_cache import compose_key_functions, extract_key_component
672
+
673
+ # Create component extractors
674
+ user_id = extract_key_component("kwargs.user_id")
675
+ api_version = extract_key_component("metadata.version")
676
+ func_name = extract_key_component("func_name")
677
+
678
+ # Compose them into a single key function
679
+ composite_key = compose_key_functions(func_name, user_id, api_version)
680
+
681
+ # Use the composite key function
682
+ task_id = await worker.add_task(
683
+ get_user_data,
684
+ user_id=123,
685
+ use_cache=True,
686
+ metadata={"version": "v2"},
687
+ cache_key_fn=composite_key
688
+ )
689
+ # Will generate a key like: "get_user_data:123:v2"
690
+ ```
691
+
692
+ #### Key Component Decorator
693
+
694
+ For better readability and reuse, you can use the decorator-based approach:
695
+
696
+ ```python
697
+ from async_cache import key_component, compose_key_functions
698
+
699
+ # Create named components with decorators
700
+ @key_component("user")
701
+ def user_component(context):
702
+ return str(context["kwargs"].get("user_id", "anonymous"))
703
+
704
+ @key_component("region")
705
+ def region_component(context):
706
+ return context["kwargs"].get("region", "global")
707
+
708
+ @key_component() # Uses function name as component name
709
+ def timestamp(context):
710
+ return context.get("metadata", {}).get("timestamp", "0")
711
+
712
+ # Compose named components
713
+ composite_key = compose_key_functions(user_component, region_component, timestamp)
714
+
715
+ # Use in a task
716
+ task_id = await worker.add_task(
717
+ get_regional_data,
718
+ user_id=123,
719
+ region="eu-west",
720
+ use_cache=True,
721
+ metadata={"timestamp": "2023-04-01"},
722
+ cache_key_fn=composite_key
723
+ )
724
+ # Will generate a key like: "user:123:region:eu-west:timestamp:2023-04-01"
725
+ ```
726
+
727
+ #### Cache Utilities
728
+
729
+ ```python
730
+ # Temporarily disable the cache (context manager)
731
+ async with worker.cache._cache.temporarily_disabled():
732
+ # Cache operations in this block will be skipped
733
+ result = await worker.add_task(my_task, arg1, arg2, use_cache=True)
734
+ # The cache is actually bypassed despite use_cache=True
735
+
736
+ # Get cache key for a specific task ID
737
+ key = await worker.cache.get_cache_key_for_task("task-123")
738
+
739
+ # Invalidate cache by task ID
740
+ await worker.cache.invalidate_by_task_id("task-123")
741
+
742
+ # Control the background cleanup task
743
+ await worker.cache.start_cleanup_task() # Start periodic cleanup
744
+ await worker.cache.stop_cleanup_task() # Stop periodic cleanup
573
745
  ```
574
746
 
575
747
  ### Cache Management
@@ -590,69 +762,125 @@ invalidated = await worker.invalidate_cache(task_func, arg1, arg2)
590
762
  await worker.clear_cache()
591
763
  ```
592
764
 
593
- ### Custom Cache Adapters
765
+ ### Cache Adapters
594
766
 
595
- By default, the task worker uses an in-memory cache, but you can create custom cache adapters for persistent storage or distributed caching.
767
+ The `async_cache` package provides several cache adapters that can be used with AsyncTaskWorker:
768
+
769
+ 1. **MemoryCacheAdapter**: In-memory LRU cache (default)
770
+ 2. **RedisCacheAdapter**: Redis-backed distributed cache
596
771
 
597
772
  ```python
598
- from async_task_worker import CacheAdapter
599
- from typing import Any, Optional, Tuple
773
+ # Using Memory Adapter (default)
774
+ from async_cache.adapters import MemoryCacheAdapter
600
775
 
776
+ memory_adapter = MemoryCacheAdapter(max_size=10000)
777
+ cache_adapter = AsyncCacheAdapter(adapter=memory_adapter)
601
778
 
602
- class RedisCache(CacheAdapter):
603
- """Example Redis-based cache adapter"""
779
+ # Using Redis Adapter
780
+ from async_cache.adapters import RedisCacheAdapter
781
+ import redis.asyncio as redis
604
782
 
605
- def __init__(self, redis_client):
606
- self.redis = redis_client
783
+ redis_client = redis.Redis(host='localhost', port=6379, db=0)
784
+ redis_adapter = RedisCacheAdapter(redis_client,
785
+ key_prefix="tasks:",
786
+ serializer="msgpack")
607
787
 
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
788
+ cache_adapter = AsyncCacheAdapter(adapter=redis_adapter)
616
789
 
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)
790
+ # Pass to AsyncTaskWorker
791
+ worker = AsyncTaskWorker(
792
+ cache_enabled=True,
793
+ cache_adapter=cache_adapter
794
+ )
795
+ ```
622
796
 
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
797
+ ### Real-World Examples
627
798
 
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)
799
+ #### Version-based Cache Invalidation
635
800
 
636
- def _serialize(self, value):
637
- # Implementation
638
- pass
801
+ ```python
802
+ # Create a cache key function that includes API version
803
+ def versioned_cache_key(context):
804
+ func = context["func_name"]
805
+ version = context.get("metadata", {}).get("api_version", "v1")
806
+ return f"{func}:{version}"
807
+
808
+ # User requests data with v1 API
809
+ task_id1 = await worker.add_task(
810
+ get_user_data,
811
+ user_id=123,
812
+ use_cache=True,
813
+ metadata={"api_version": "v1"},
814
+ cache_key_fn=versioned_cache_key
815
+ )
639
816
 
640
- def _deserialize(self, data):
641
- # Implementation
642
- pass
817
+ # Later, after API update, same data with v2 API
818
+ # Will use a different cache key, not reusing v1 cached result
819
+ task_id2 = await worker.add_task(
820
+ get_user_data,
821
+ user_id=123,
822
+ use_cache=True,
823
+ metadata={"api_version": "v2"},
824
+ cache_key_fn=versioned_cache_key
825
+ )
826
+ ```
643
827
 
828
+ #### Multi-tenant Cache Isolation
644
829
 
645
- # Use custom adapter
646
- import redis.asyncio as redis
830
+ ```python
831
+ # Create a key function that isolates cache by tenant
832
+ tenant_key = compose_key_functions(
833
+ extract_key_component("func_name"),
834
+ extract_key_component("metadata.tenant_id"),
835
+ extract_key_component("args.0") # First arg value
836
+ )
647
837
 
648
- redis_client = redis.Redis(host='localhost', port=6379, db=0)
838
+ # Different tenants share same function but get isolated cache
839
+ for tenant_id in ["tenant1", "tenant2", "tenant3"]:
840
+ task_id = await worker.add_task(
841
+ process_data,
842
+ "sample_data",
843
+ use_cache=True,
844
+ metadata={"tenant_id": tenant_id},
845
+ cache_key_fn=tenant_key
846
+ )
847
+ ```
848
+
849
+ ### Automatic Cleanup of Stale Mappings
850
+
851
+ The cache system includes an automatic cleanup mechanism to prevent memory leaks from orphaned task ID mappings when cache entries expire through TTL:
649
852
 
853
+ ```python
854
+ # Configure a worker with cleanup enabled
650
855
  worker = AsyncTaskWorker(
651
- cache_enabled=True,
652
- cache_adapter=RedisCache(redis_client)
856
+ cache_enabled=True,
857
+ cache_ttl=3600, # 1 hour cache TTL
858
+ cleanup_interval=900 # Clean up stale mappings every 15 minutes
859
+ )
860
+
861
+ # The sequence of events:
862
+ # 1. Add a task with caching enabled
863
+ task_id = await worker.add_task(
864
+ process_data,
865
+ dataset,
866
+ use_cache=True,
867
+ cache_ttl=60 # 1 minute TTL
653
868
  )
869
+
870
+ # 2. The task_id is mapped to its cache key in task_key_map
871
+
872
+ # 3. After 1 minute, the cache entry expires due to TTL
873
+
874
+ # 4. Without cleanup, the mapping would remain in memory indefinitely
875
+
876
+ # 5. With cleanup enabled, the background task periodically checks
877
+ # all mappings and removes any where the cache entry is gone
878
+
879
+ # 6. Result: No memory leaks from expired cache entries
654
880
  ```
655
881
 
882
+ 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.
883
+
656
884
  ## Advanced Usage
657
885
 
658
886
  ### Task Registry
@@ -747,16 +975,32 @@ print(f"Task failed: {info.error}") # "Value cannot be negative"
747
975
 
748
976
  ### AsyncTaskWorker
749
977
 
750
- - `__init__(max_workers=10, task_timeout=None)`: Initialize worker pool
978
+ - `__init__(max_workers=10, task_timeout=None, cache_adapter=None, cache_enabled=False, cache_ttl=3600)`: Initialize worker pool
751
979
  - `start()`: Start the worker pool
752
980
  - `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
981
+ - `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
982
  - `get_task_info(task_id)`: Get information about a task
755
983
  - `get_all_tasks(status=None, limit=None, older_than=None)`: Get filtered list of tasks
756
984
  - `cancel_task(task_id)`: Cancel a running or pending task
757
985
  - `get_task_future(task_id)`: Get a future that resolves when the task completes
758
986
  - `wait_for_tasks(task_ids, timeout=None)`: Wait for multiple tasks to complete
759
987
  - `wait_for_any_task(task_ids, timeout=None)`: Wait for any of the specified tasks to complete
988
+ - `invalidate_cache(task_func, *args, cache_key_fn=None, **kwargs)`: Invalidate a specific cache entry
989
+ - `clear_cache()`: Clear all cache entries
990
+
991
+ ### AsyncCacheAdapter
992
+
993
+ - `__init__(default_ttl=None, enabled=True, max_serialized_size=10485760, validate_keys=False, cleanup_interval=900, max_size=1000)`: Initialize the cache adapter
994
+ - `get(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Get cached result
995
+ - `set(func_name, args, kwargs, result, ttl=None, cache_key_fn=None, task_id=None, metadata=None)`: Store result in cache
996
+ - `invalidate(func_name, args, kwargs, cache_key_fn=None, task_id=None, metadata=None)`: Invalidate specific cache entry
997
+ - `invalidate_by_task_id(task_id)`: Invalidate by task ID
998
+ - `clear()`: Clear the entire cache
999
+ - `start_cleanup_task()`: Start the periodic cleanup task
1000
+ - `stop_cleanup_task()`: Stop the periodic cleanup task
1001
+ - `enabled`: Property to get/set if cache is enabled
1002
+ - `default_ttl`: Property to get/set default TTL
1003
+ - `cleanup_interval`: Property to get/set cleanup interval
760
1004
 
761
1005
  ### WorkerPool
762
1006