22import logging
33from collections .abc import Awaitable , Callable
44from datetime import timedelta
5- from typing import TypedDict
65
76from fastapi import FastAPI
87from servicelib .async_utils import cancel_wait_task
1211from .background_tasks import removal_policy_task
1312from .modules .redis import get_redis_lock_client
1413
15-
16- @exclusive_periodic (
17- get_redis_lock_client ,
18- task_interval = timedelta (hours = 1 ),
19- retry_after = timedelta (minutes = 5 ),
20- )
21- async def periodic_removal_policy_task (app : FastAPI ) -> None :
22- await removal_policy_task (app )
23-
24-
2514_logger = logging .getLogger (__name__ )
2615
2716
28- class EfsGuardianBackgroundTask (TypedDict ):
29- name : str
30- task_func : Callable
31-
32-
33- _EFS_GUARDIAN_BACKGROUND_TASKS = [
34- EfsGuardianBackgroundTask (
35- name = "efs_removal_policy_task" , task_func = periodic_removal_policy_task
36- )
37- ]
38-
39-
4017def _on_app_startup (app : FastAPI ) -> Callable [[], Awaitable [None ]]:
4118 async def _startup () -> None :
4219 with (
43- log_context (_logger , logging .INFO , msg = "Efs Guardian startup.. " ),
20+ log_context (_logger , logging .INFO , msg = "Efs Guardian background task " ),
4421 log_catch (_logger , reraise = False ),
4522 ):
46- app .state .efs_guardian_background_tasks = []
23+ app .state .efs_guardian_removal_policy_background_task = None
4724
48- # Setup periodic tasks
49- for task in _EFS_GUARDIAN_BACKGROUND_TASKS :
50- app .state .efs_guardian_background_tasks .append (
51- asyncio .create_task (task ["task_func" ](), name = task ["name" ])
52- )
25+ _logger .info ("starting efs guardian removal policy task" )
26+
27+ @exclusive_periodic (
28+ get_redis_lock_client (app ),
29+ task_interval = timedelta (hours = 1 ),
30+ retry_after = timedelta (minutes = 5 ),
31+ )
32+ async def _periodic_removal_policy_task () -> None :
33+ await removal_policy_task (app )
34+
35+ app .state .efs_guardian_removal_policy_background_task = asyncio .create_task (
36+ _periodic_removal_policy_task (),
37+ name = _periodic_removal_policy_task .__name__ ,
38+ )
5339
5440 return _startup
5541
@@ -63,12 +49,9 @@ async def _stop() -> None:
6349 log_catch (_logger , reraise = False ),
6450 ):
6551 assert _app # nosec
66- if _app .state .efs_guardian_background_tasks :
67- await asyncio .gather (
68- * [
69- cancel_wait_task (task )
70- for task in _app .state .efs_guardian_background_tasks
71- ]
52+ if _app .state .efs_guardian_removal_policy_background_task :
53+ await cancel_wait_task (
54+ _app .state .efs_guardian_removal_policy_background_task
7255 )
7356
7457 return _stop
0 commit comments